使用PHP保存XML文档时出现编码错误(HTML实体)
我用PHP创建XML文件,这是我得到的输出使用PHP保存XML文档时出现编码错误(HTML实体),php,xml,wordpress,domdocument,html-entities,Php,Xml,Wordpress,Domdocument,Html Entities,我用PHP创建XML文件,这是我得到的输出 error on line 2 at column 165: Encoding error Below is a rendering of the page up to the first error. 在源代码中,我只看到了这一点 <?xml version="1.0" encoding="UTF-8"?> <ad_list><ad_item class="class"><description_raw&g
error on line 2 at column 165: Encoding error
Below is a rendering of the page up to the first error.
在源代码中,我只看到了这一点
<?xml version="1.0" encoding="UTF-8"?>
<ad_list><ad_item class="class"><description_raw>Lorem ipsum dolor sit amet
如果我从description\u raw
中删除html\u entity\u decode
函数,则会生成完整的XML,但我有此错误
error on line 6 at column 7: Entity 'nbsp' not defined
Below is a rendering of the page up to the first error.
您获得的值在XML文档中很可能是有效的。您应该将其添加为CDATA部分。试着这样做:
<?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);
createElement(“广告列表”);
$ad_item=$xml->createElement(“ad_item”);
$xml\u item->appendChild($ad\u item);
$description_raw=$xml->createElement(“description_raw”);
$cdata=$xml->CreateCataSection(获取内容());
$description\u raw->appendChild($cdata);
$ad_item->appendChild($description_raw);
$xml->appendChild($xml\u项);
$xml->save($filename);
或者,只需自己构建:
<?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);
XML;
文件内容($filename,$xml);
在XML中不是有效的实体,对其进行解码是正确的方法。但是您使用的是DOMDocument::createElement()
的第二个参数。这是坏的:
<?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);