PHP DOMDocument获取h3标签下一个p兄弟节点文本返回空字符串问题
问题原因
nextSibling 属性会返回所有类型的相邻节点,包括标签之间的空白字符(换行、空格)生成的文本节点,你拿到的空内容节点其实是h3和p标签之间的空白文本节点,不是你要的p元素节点。
解决方案
方案1:跳过非元素节点,定位目标p标签
修改遍历逻辑,过滤掉文本、注释等非元素节点,直到找到下一个p元素:
foreach ($hList as $k=>$h ) { $text = $h->nodeValue ; dump( 'h3->' , $text); $nextNode = $h->nextSibling; // 循环跳过非元素节点 while ($nextNode !== null && $nextNode->nodeType !== XML_ELEMENT_NODE) { $nextNode = $nextNode->nextSibling; } // 确认是p标签再取值 if ($nextNode !== null && $nextNode->tagName === 'p') { dump( 'p->' , $nextNode->nodeValue); } }
方案2:用XPath直接精准查询
直接通过XPath规则定位每个h3后紧跟的第一个p节点,逻辑更简洁高效:
$doc = new \DOMDocument('1.0', 'UTF-8'); $prologue = '<?xml encoding="UTF-8">'; @$doc->loadHTML($prologue.$page); // 加@抑制非规范HTML的警告 $finder = new \DOMXPath($doc); $h3Nodes = $finder->query("//*[contains(@class, 'td-post-content td-pb-padding-side')]/h3"); foreach ($h3Nodes as $h3) { $pNode = $finder->query("./following-sibling::p[1]", $h3)->item(0); dump('h3->', $h3->nodeValue); if ($pNode) { dump('p->', $pNode->nodeValue); } }
内容的提问来源于stack exchange,提问作者hretic
相关产品推荐
相关产品推荐

