【问题标题】:Encoding error when saving XML document with PHP (HTML entities)使用 PHP(HTML 实体)保存 XML 文档时出现编码错误
【发布时间】:2017-09-03 05:33:57
【问题描述】:

我正在用 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>Lorem ipsum dolor sit amet &#13;
&#13;
&#13;
&#13;

这是我正在使用的代码(strip_shortcodes 是用于删除 Wordpress 使用的标签的 Wordpress 函数)。

$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); 

如果我从 description_raw 中删除 html_entity_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.

【问题讨论】:

  • &amp;nbsp; 不是 XML 中的有效实体,解码它是正确的方法。但是您使用的是DOMDocument::createElement() 的第二个参数。这是坏的:stackoverflow.com/questions/22956330/…

标签: php xml wordpress domdocument html-entities


【解决方案1】:

您获得的值在 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);

或者,自己构建它:

<?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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2021-12-15
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2014-01-10
    相关资源
    最近更新 更多