编程语言
首页 > 编程语言> > php – 防止DOMDocument :: loadHTML()转换实体

php – 防止DOMDocument :: loadHTML()转换实体

作者:互联网

我有一个字符串值,我正在尝试提取列表项.我想提取文本和任何子节点,但是,DOMDocument正在将实体转换为角色,而不是保留原始状态.

我已经尝试将DOMDocument :: resolveExternals和DOMDocument :: substituteEntities设置为false,但这没有任何效果.应该注意我使用PHP 5.2.17在Win7上运行.

示例代码是:

$example = '<ul><li>text</li>'.
    '<li>&frac12; of this is <strong>strong</strong></li></ul>';

echo 'To be converted:'.PHP_EOL.$example.PHP_EOL;

$doc = new DOMDocument();
$doc->resolveExternals = false;
$doc->substituteEntities = false;

$doc->loadHTML($example);

$domNodeList = $doc->getElementsByTagName('li');
$count = $domNodeList->length;

for ($idx = 0; $idx < $count; $idx++) {
    $value = trim(_get_inner_html($domNodeList->item($idx)));
    /* remainder of processing and storing in database */
    echo 'Saved '.$value.PHP_EOL;
}

function _get_inner_html( $node ) {
    $innerHTML= '';
    $children = $node->childNodes;
    foreach ($children as $child) {
        $innerHTML .= $child->ownerDocument->saveXML( $child );
    }

    return $innerHTML;
}

&安培; frac12;最终转换为½(单字符/ UTF-8版本,而不是实体版本),这不是所需的格式.

解决方法:

不是PHP 5.3.6的解决方案

$html =<<<HTML
<ul><li>text</li>
<li>&frac12; of this is <strong>strong</strong></li></ul>
HTML;

$doc = new DOMDocument();
$doc->resolveExternals = false;
$doc->substituteEntities = false;
$doc->loadHTML($html);
foreach ($doc->getElementsByTagName('li') as $node)
{
  echo htmlentities(iconv('UTF-8', 'ISO-8859-1', $node->nodeValue)), "\n";
}

标签:php,dom,domdocument,php-5-2
来源: https://codeday.me/bug/20190613/1235957.html