php – 防止DOMDocument :: loadHTML()转换实体
发布时间:2020-12-13 17:39:11 所属栏目:PHP教程 来源:网络整理
导读:我有一个字符串值,我正在尝试提取列表项.我想提取文本和任何子节点,但是,DOMDocument正在将实体转换为角色,而不是保留原始状态. 我已经尝试将DOMDocument :: resolveExternals和DOMDocument :: substituteEntities设置为false,但这没有任何效果.应该注意我使
我有一个字符串值,我正在尝试提取列表项.我想提取文本和任何子节点,但是,DOMDocument正在将实体转换为角色,而不是保留原始状态.
我已经尝试将DOMDocument :: resolveExternals和DOMDocument :: substituteEntities设置为false,但这没有任何效果.应该注意我使用PHP 5.2.17在Win7上运行. 示例代码是: $example = '<ul><li>text</li>'. '<li>½ 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>½ 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"; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |