Tho*_*mas 2 html php tags parsing domdocument
我正在寻找这个功能:
给定的是这个html-Page:
<body>
<h1>Hello,
<b>world!</b>
</h1>
</body>
Run Code Online (Sandbox Code Playgroud)
我想得到一个只包含DISTINCT文本元素(没有重复)的数组和一个围绕文本元素的标记数组:
上面的"html"的结果将是一个如下所示的数组:
array =>
"Hello," surrounded by => "h1" and "body"
"world!" surrounded by => "b", "h1" and "body"
Run Code Online (Sandbox Code Playgroud)
我还是这样做的:
$res=$xpath->query("//body//*/text()");
Run Code Online (Sandbox Code Playgroud)
这给了我不同的文本内容,但省略了html标签.
当我这样做时:
$res=$xpath->query("//body//*");
Run Code Online (Sandbox Code Playgroud)
我得到重复的文本,每个标签星座一个:例如:"世界!" 将出现3次,一次为"body",一次为"h1",一次为"b"但我似乎无法获得哪些文本是实际重复的信息.仅检查重复文本是不够的,因为重复文本有时只是以前文本的子字符串,或者网站可能包含真正的重复文本,然后丢弃这些文本是错误的.
我怎么能解决这个问题?
非常感谢你!!
托马斯
您可以遍历parentNodes中的一个DOMText节点:
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$textNodes = array();
foreach($xpath->query('/html/body//text()') as $i => $textNode) {
$textNodes[$i] = array(
'text' => $textNode->nodeValue,
'parents' => array()
);
for (
$currentNode = $textNode->parentNode;
$currentNode->parentNode;
$currentNode = $currentNode->parentNode
) {
$textNodes[$i]['parents'][] = $currentNode->nodeName;
}
}
print_r($textNodes);
Run Code Online (Sandbox Code Playgroud)
请注意,loadHTML将添加隐含元素,例如,它将添加html和head元素,在使用XPath时您将不得不考虑这些元素.另请注意,用于格式化的任何空格都被视为DOMText,因此您可能会获得比预期更多的元素.如果您只想查询非空的DOMText节点使用
/html/body//text()[normalize-space(.) != ""]
Run Code Online (Sandbox Code Playgroud)