Gor*_*don 7 php xhtml xpath utf-8
我有一个XHTML文档通过Greasemonkey AJAX传递给PHP应用程序.PHP应用程序使用UTF8.如果我将POST内容直接输回到AJAX接收div中的textarea,则所有内容仍然以UTF8正确编码.
当我尝试使用XPath进行解析时
$dom = new DOMDocument();
$dom->loadHTML($raw2);
$xpath = new DOMXPath($dom);
$query = '//td/text()';
$nodes = $xpath->query($query);
foreach($nodes as $node) {
var_dump($node->wholeText);
}
Run Code Online (Sandbox Code Playgroud)
倾销的字符串不是utf8.如何强制DOM/XPath使用UTF8?
Luc*_*cia 31
我有同样的问题,我无法在我的网络服务器中使用整洁.我找到了这个解决方案,它运行良好:
$html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"); $dom = new DomDocument(); $dom->loadHTML($html);
小智 7
游戏有点晚了,但也许它对某人有帮助......
\n\n问题可能出在输出中,而不是 dom/xpath 对象本身。
\n\n如果直接输出 nodeValue,则会得到损坏的字符,例如:
\n\n\xc3\x83\xc2\xac\xc3\x82\xc3\x82\xc3\x83\xc2\xac\xc3\x82\xc3\x82 \xc3\x83\xc2\xab\xc3\x82\xc2\xb9\xc3\x82\xc3\x83\xc2\xab\xc3\x82\xe2\x80\x9d\xc3\x82\xe2\x80\x9d\xc3\x83\xc2\xac\xc3\x82\xc3\x82\xc2\xa4\n\xc3\xac\xc3\xac \xc3\xab\xc2\xb9\xc3\xab\xe2\x80\x9d\xe2\x80\x9d\xc3\xac\xc2\xa4 \xc3\xad\xc2\xb0\xc3\xac \xc3\xad\xc3\xac\xc2\xa4\nRun Code Online (Sandbox Code Playgroud)\n\n你必须使用第二个参数“utf-8”加载你的dom对象,new \\DomDocument(\'1.0\', \'utf-8\')但是当您打印 dom 节点列表/元素值时,您仍然会得到损坏的字符:
echo $contentItem->item($index)->nodeValue
你必须用 utf8_decode 来包装它:
\n\necho utf8_decode($contentItem->item($index)->nodeValue)\n//output: \xe8\x80\x85\xe4\xb8\x8d\xe7\xb5\x82\xe6\x9c\x9d\xe8\x80\x8c\xe6\x9c\x83\xef\xbc\x8c\xe6\x84\x9a\xe8\x80\x85\xe5\x8f\xaf\xe6\xb5\xb9\xe6\x97\xac\xe8\x80\x8c\xe5\xad\xb8\n
如果它是一个完全成熟的有效 xhtml 文档,则不应使用 loadhtml(),而应使用 load()/loadxml()。
\n\n给出示例 xhtml 文档
\n\n<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n <head>\n <title>xhtml test</title>\n </head>\n <body>\n <h1>A Table</h1>\n <table>\n <tr><th>A</th><th>O</th><th>U</th></tr>\n <tr><td>\xc3\x84</td><td>\xc3\x96</td><td>\xc3\x9c</td></tr>\n <tr><td>\xc3\xa4</td><td>\xc3\xb6</td><td>\xc3\xbc</td></tr>\n </table>\n </body>\n</html>\nRun Code Online (Sandbox Code Playgroud)\n\n剧本
\n\n<?php\n$raw2 = \'test.html\';\n\n$dom = new DOMDocument();\n$dom->load($raw2);\n$xpath = new DOMXPath($dom);\nvar_dump($xpath->registerNamespace(\'h\', \'http://www.w3.org/1999/xhtml\'));\n$query = \'//h:td/text()\';\n$nodes = $xpath->query($query);\nforeach($nodes as $node) {\n foo($node->wholeText);\n}\n\n\nfunction foo($s) {\n for($i=0; $i<strlen($s); $i++) {\n printf(\'%02X \', ord($s[$i]));\n }\n echo "\\n";\n}\nRun Code Online (Sandbox Code Playgroud)\n\n印刷
\n\nbool(true)\nC3 84 \nC3 96 \nC3 9C \nC3 A4 \nC3 B6 \nC3 BC \nRun Code Online (Sandbox Code Playgroud)\n\n即输出/字符串是 utf-8 编码的
\n| 归档时间: |
|
| 查看次数: |
10596 次 |
| 最近记录: |