Md. Yusuf
Md. Yusuf

Reputation: 522

How to handle & and other special character in SimpleXML PHP

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.

Upvotes: 4

Views: 8705

Answers (2)

Rizier123
Rizier123

Reputation: 59701

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>

Upvotes: 2

szapio
szapio

Reputation: 1008

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();

Upvotes: 3

Related Questions