4

I have used SimpleXMLElement for creating xml But it cannot handle &. Here is my code

$contacts = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Contacts></Contacts>');
$name = $contacts->addChild('name', 'You & Me');
$name->addAttribute('no', '1');
echo $contacts->asXML();

And here is the output

<?xml version="1.0" encoding="UTF-8"?>
<Contacts><name no="1">You </name></Contacts>

How to solve this Question. I want a solution for all special character.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Md. Yusuf
  • 502
  • 2
  • 6
  • 20

2 Answers2

3

You have to replace it with e.g html code http://www.ascii.cl/htmlcodes.htm or check this http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

$contacts = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Contacts></Contacts>');
$name = $contacts->addChild('name', 'You &amp; Me');
$name->addAttribute('no', '1');
echo $contacts->asXML();

you can use also a function htmlspecialchars to do it

$contacts = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Contacts></Contacts>');
$name = $contacts->addChild('name', htmlspecialchars('You & Me', ENT_QUOTES, "utf-8"));
$name->addAttribute('no', '1');
echo $contacts->asXML();
szapio
  • 998
  • 1
  • 9
  • 15
2

This should work for you without using html codes, because this way it automatically escapes it:

(Because addChild() only escapes < and >, but not &)

$contacts = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Contacts></Contacts>');
$contacts->name[0] = 'You & Me';
$contacts->name[0]->addAttribute('no', '1');
echo $contacts->asXML();

Output (Source code):

<?xml version="1.0" encoding="UTF-8"?>
<Contacts><name no="1">You &amp; Me</name></Contacts>
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • If I have more then one child with same name then what to do ?? – Md. Yusuf Feb 23 '15 at 08:29
  • 1
    @Md.Yusuf Then make sure to specify it like this: `$contacts->name[2] = 'You & Me';` And if you don't know the number and just want to append one do: `$contacts->name[] = 'You & Me';` – Rizier123 Feb 23 '15 at 08:49
  • @Md.Yusuf BTW: If you want a full explanation why this is handled like this see this: http://stackoverflow.com/q/552957/3933332 – Rizier123 Feb 23 '15 at 08:52