gpt4 book ai didi

php/xpath : Getting the content in nested divs

转载 作者:行者123 更新时间:2023-12-02 17:52:21 27 4
gpt4 key购买 nike

我有以下 html 代码:

<div class='class1'> Content 1
<div class='class2'> Content 2
</div>
</div>

我想使用 xpath 仅获取“class1”和“class2”之间的内容,即“Content 1”本身。这是我到目前为止所拥有的:

$classname = 'class1';
$results = $xpath->query("//*[@class='" . $classname . "']");
echo $results->item($x)->nodeValue;

但是它又回来了

Content 1 Content 2

无论如何,只获取“内容 1”本身?谢谢!

最佳答案

很难确切地知道您的代码出了什么问题,因为我们不知道 $x 代表什么。您拥有的 XPath 是正确的,但从您的代码中我无法判断您如何打印输出。以下是我认为您想要实现的目标的一个工作示例:

PHP

<?php

$string =
<<<XML
<div class='class1'> Content 1
<div class='class2'> Content 2
</div>
</div>
XML;

$xml = new SimpleXMLElement($string);

$results = $xml->xpath('//div[@class="class1"]');
foreach($results as $result) {
echo $result;
}

?>

输出

Content 1

这将创建一个“简单的 xml 元素”,然后使用 XPath //div[@class="class1"] 查找所需的元素。返回的 $results 变量是一个数组(仅包含一个元素),因此我循环遍历它以打印所需的输出。

关于php/xpath : Getting the content in nested divs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33333699/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com