0

I am creating XML file with PHP, this is the output I get

error on line 2 at column 165: Encoding error
Below is a rendering of the page up to the first error.

In the source I see only this

<?xml version="1.0" encoding="UTF-8"?>
<ad_list><ad_item class="class"><description_raw>Lorem ipsum dolor sit amet &#13;
&#13;
&#13;
&#13;

This is the code I am using (strip_shortcodes is Wordpress function for removing tags that Wordpress uses).

$xml = new DOMDocument('1.0', 'UTF-8'); 
$xml__item = $xml->createElement("ad_list");    

$ad_item = $xml->createElement("ad_item");
$xml__item->appendChild( $ad_item );

$description_raw = $xml->createElement("description_raw", strip_shortcodes(html_entity_decode(get_the_content())));
$ad_item->appendChild( $description_raw );

$xml->appendChild( $xml__item );
$xml->save($filename); 

If I remove html_entity_decode function from description_raw than full XML is generated but then I have this error

error on line 6 at column 7: Entity 'nbsp' not defined
Below is a rendering of the page up to the first error.
Ivan Topić
  • 3,064
  • 6
  • 34
  • 47
  • 1
    ` ` is not a valid entity in XML, decoding it is the right way. But you're using the second argument of `DOMDocument::createElement()`. This is broken: http://stackoverflow.com/questions/22956330/cakephp-xml-utility-library-triggers-domdocument-warning/22957785#22957785 – ThW Apr 09 '17 at 12:58

1 Answers1

0

It's highly unlikely that the value you're getting is going to be valid in an XML document. You should be adding it as a CDATA section. Try something like this:

<?php
$xml = new DOMDocument('1.0', 'UTF-8'); 
$xml__item = $xml->createElement("ad_list");    

$ad_item = $xml->createElement("ad_item");
$xml__item->appendChild( $ad_item );

$description_raw = $xml->createElement("description_raw");
$cdata = $xml->createCDATASection(get_the_content());
$description_raw->appendChild($cdata);
$ad_item->appendChild( $description_raw );

$xml->appendChild( $xml__item );
$xml->save($filename);

Alternatively, just build it yourself:

<?php
$content = get_the_content();
$xml = <<< XML
<?xml version="1.0"?>
<ad_list>
    <ad_item>
        <description_raw><![CDATA[ $content ]]></description_raw>
    </ad_item>
</ad_list>

XML;
file_put_contents($filename, $xml);
Adam Lear
  • 38,111
  • 12
  • 81
  • 101
miken32
  • 42,008
  • 16
  • 111
  • 154