Generating XML document in PHP escape characters

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m generating an XML document from a PHP script and I need to escape the XML special characters. I know the list of characters that should be escaped; but what is the correct way to do it?

Should the characters be escaped just with backslash ( ) or what is the proper way? Is there any built-in PHP function that can handle this for me?

Answers

http://www.php.net/manual/en/book.dom.php http://www.php.net/manual/en/book.dom.php


 Edit:   This was criticized by @Tchalvak:
The DOM object creates a full XML document, it doesn t easily lend itself to just encoding a string on it s own.

Which is wrong, DOMDocument can properly output just a fragment not the whole document:

$doc->saveXML($fragment);

which gives:

Test &amp; <b> and encode </b> :)
Test &amp;amp; &lt;b&gt; and encode &lt;/b&gt; :)

as in:

$doc = new DOMDocument();
$fragment = $doc->createDocumentFragment();

// adding XML verbatim:
$xml = "Test &amp; <b> and encode </b> :)
";
$fragment->appendXML($xml);

// adding text:
$text = $xml;
$fragment->appendChild($doc->createTextNode($text));

// output the result
echo $doc->saveXML($fragment);

http://eval.in/10247 http://eval.in/10247

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/3957360/generating-xml-document-in-php-escape-characters

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils