3

这是怎么回事?

$string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
    <album>
        <img src="002.jpg" caption="w&aacute;ssup?" />
    </album>
XML;

$xml = simplexml_load_string($string);
// $xmlobj = simplexml_load_file("xml.xml"); // same thing

echo "<pre>";
var_dump($xml);
echo "</pre>";

错误:

警告:simplexml_load_string() [function.simplexml-load-string]:实体:第 5 行:解析器错误:未定义实体“aacute”

4

5 回答 5

14

&aacute不是XML 实体- 您正在考虑 HTML。

特殊字符通常在 XML 中“按原样”使用 -html_entity_decode()在输入数据上(不要忘记将 UTF-8 指定为字符集)应该可以解决问题:

$string = html_entity_decode($string, ENT_QUOTES, "utf-8");
于 2010-05-17T16:14:03.867 回答
2

前几天我遇到了这个问题。任何出现的 & 都需要在 CDATA 标记内

<album>
    <img src="002.jpg" />
    <caption><![CDATA[now you can put whatever characters you need & include html]]></caption>
</album> 

以防止解析器失败。

于 2010-05-17T16:14:50.780 回答
2

您可能想查看Matt Robinson关于替代方法的文章:在 PHP 中将命名实体转换为数字。它提到了html_entity_decode方法(已经由另一个答案指出)和一些潜在的陷阱:

这种方法有两个可能的问题。第一个是无效实体:html_entity_decode()不会触及它们,这意味着您仍然会收到 XML 错误。二是编码。我想你可能并不真正想要UTF-8. 你应该,因为它很棒,但也许你有充分的理由。如果您不告诉html_entity_decode() 使用UTF-8,它不会转换您指定的字符集中不存在的实体。如果您告诉它以 UTF-8 输出,然后使用类似的东西iconv()进行转换,那么您将丢失任何不在输出编码中的字符。

另外,如果您觉得脚本比较麻烦,您也可以使用SourceRally 上共享的脚本

于 2010-05-17T16:30:33.353 回答
1

另一个解决方案是改变

"w&aacute;ssup?" to "w&amp;aacute;ssup?"

于 2014-04-12T11:35:48.303 回答
0

试试这个功能simplexml_load_entity_string

<?php

$string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
    <album>
        <img src="002.jpg" caption="test&lt;w&aacute;ssup?" />
    </album>
XML;

$xml = simplexml_load_entity_string($string);

var_dump($xml);

function simplexml_load_entity_string($string = '')
{
    // cover entity except Predefined entities in XML
    $string = str_replace([
        '&quot;', '&amp;', '&apos;', '&lt;', '&gt;',
    ], [
        'SPECIALquotMARK', 'SPECIALampMARK', 'SPECIALaposMARK', 'SPECIALltMARK', 'SPECIALgtMARK',
    ], $string);
    $string = html_entity_decode($string, ENT_QUOTES, "utf-8");
    $string = str_replace([
        'SPECIALquotMARK', 'SPECIALampMARK', 'SPECIALaposMARK', 'SPECIALltMARK', 'SPECIALgtMARK',
    ], [
        '&quot;', '&amp;', '&apos;', '&lt;', '&gt;',
    ], $string);

    // load xml
    return simplexml_load_string($string);
}
于 2018-02-26T10:18:06.057 回答