Declaring an object in the php-formation of an XML document (& nbsp; & mdash; etc.)

It drives me crazy, there are many similar problems on the Internet, but I canโ€™t find the right solution.

I am creating an XML document in php to send as a response to an ajax request. The answer will look something like this:

<?xml version="1.0" encoding="iso-8859-1"?>
<response>
  <status>success</status>
  <message>&nbsp;&mdash;</message>
</response>

The tag will contain more meaningful information than that, but these are entities similar to those that give me the problem.

The php code that this xml generates is below:

header("Content-Type: text/xml");

$dom = new DOMDocument('1.0', 'iso-8859-1');
$dom->formatOutput = true;

$response_node = $dom->createElement("response");
$dom->appendChild($response_node);
$response_node->appendChild($dom->createElement('status', 'success'));
$response_node->appendChild($dom->createElement('message', "&nbsp;&mdash"));
echo $dom->saveXML();
return;

The xml shown above successfully returns to the javascript function that made the call, but when it tries to parse the XML document, it fails.

If I try to validate xml using this validator , I get the following error:

This page contains the following errors:

5 15: Entity 'nbsp'

&mdash; .

, - xml:

<!ENTITY name "entity_value">

, , . ? , ? , ?

+3
3

, doctype, :

$dom = new DOMDocument('1.0', 'iso-8859-1');
$dom->formatOutput = true;
$doctype = DOMImplementation::createDocumentType("html","-//W3C//DTD XHTML 1.1//EN","http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd");
$dom->appendChild($doctype);

$response_node = $dom->createElement("response");
$dom->appendChild($response_node);
$response_node->appendChild($dom->createElement('status', 'success'));
$response_node->appendChild($dom->createElement('message', "&nbsp;&mdash"));
echo $dom->saveXML();
return;
+2

HTML XML, <!ENTITY name "...">, . .

:

&nbsp; = > &#xA0;

&mdash; = > &#x2014;

+2

- UTF-8, XML.

, XML, , XML, HTML:

PHP 5.4.0 +:

$encoded_value = htmlentities($value, ENT_COMPAT | ENT_XML1);

In older versions of PHP, the standard encoding is ISO-8859-1, so specify UTF-8 as the encoding:

$encoded_value = htmlentities($value, ENT_COMPAT | ENT_XML1, 'UTF-8');

Note: you can use the html_entity_decode function to get - from the mdash object.

+1
source

All Articles