Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle & and other special character in SimpleXML PHP

Tags:

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.

like image 928
Md. Yusuf Avatar asked Oct 12 '25 11:10

Md. Yusuf


1 Answers

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();
like image 130
szapio Avatar answered Oct 15 '25 03:10

szapio