PHP DOMXPath使用示例,帮助理解evaluate、query及获取3种结果方式
2025-4-07 18:56:32
示例代码:
<?php
$html = <<<HTML
<article>
<h2>Article Title</h2>
<div class="entry-content">你好
<p>This is the content of the article.</p>
<p>This is the content of the article.</p>
<p>This is the content of the <span>article</span>.</p>
</div>
</article>
HTML;
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$title = $xpath->evaluate('string(//h2');
// 查询 div 元素
$contentNode = $xpath->query('//div[@class="entry-content"]')->item(0);
// 初始化内容字符串
$content = '';
// 检查是否找到了目标节点
if ($contentNode) {
// 遍历目标节点的所有子节点
foreach ($contentNode->childNodes as $childNode) {
// 将每个子节点保存为 HTML 字符串并拼接到内容中
$content .= $dom->saveHTML($childNode);
}
}
$contentNode2 = $xpath->query('//div[@class="entry-content"]')->item(0);
// 获取该节点及其子节点的 HTML 内容
if ($contentNode2) {
$content2 = $dom->saveHTML($contentNode2);
} else {
$content2 = '';
}
$content3 = $xpath->evaluate('string(//div[@class="entry-content"])');
echo "Title: $titlen";
echo "Content: $contentn";
echo "Content: $content2n";
echo "Content: $content3n";
?>
输出结果:
Title: Article Title
Content: 你好
<p>This is the content of the article.</p>
<p>This is the content of the article.</p>
<p>This is the content of the <span>article</span>.</p>
Content2: <div class="entry-content">你好
<p>This is the content of the article.</p>
<p>This is the content of the article.</p>
<p>This is the content of the <span>article</span>.</p>
</div>
Content3: 你好
This is the content of the article.
This is the content of the article.
This is the content of the article.