gpt4 book ai didi

php - 使用XPath计算每个表中的TH数

转载 作者:行者123 更新时间:2023-12-03 16:23:31 30 4
gpt4 key购买 nike

卡在一个兔子洞中,试图解析HTML文件。
基础:

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile('myfile.html');
$xp = new DOMXPath($dom);

初始化之后,我的技术一直是使用XPATH查询来获取所需的变量。
实际上,如果有一个特定的项目或节点,我没有任何问题-非常容易查明和检索。
因此,在我加载的HTML中,它基本上是循环形成的。缩小后看起来像这样:
<div class="intro">
<div class="desc-wrap">
Text Text Text
</div>
<div class="main-wrap">
<table class="table-wrap">
<tbody>
<tr>
<th class="range">Range </th>
<th>#1</th>
<th>#2</th>
</tr>
</tbody>
</table>
</div>
</div>
<div class="intro">
<div class="desc-wrap">
Text Text Text
</div>
<div class="main-wrap">
<table class="table-wrap">
<tbody>
<tr>
<th class="range">Range </th>
<th>#1</th>
<th>#2</th>
<th>#3</th>
<th>#4</th>
</tr>
</tbody>
</table>
</div>
</div>

这持续了100次(表示 <div class="intro"> . . . </div>的100个实例
因此,我试图获取 desc-wrap的内容(那里没有问题),以及文本节点以及每个表中有多少 <th>的计数。
我认为div可能是一个XPath查询可能优于两个查询。
$intropath = $xp->query("//div[@class='intro']");

循环播放。
$f=1;
foreach ($intropath as $sp) {
echo $f++ . '<br />'; // Makes it way to 100, good.

我遇到的问题/核心问题是尝试计算每个表中 <th>的数量。
$gettables = $xp->query("//div[contains(@class,'main-wrap')]/table[contains(@class, 'table-wrap')]//th", $sp);
var_dump($getsizes); // public 'length' => int 488
// Okay, so this is getting all the <th> elements in the
// entire document, not just in the loop. Maybe not what I want.

这是我尝试过的其他事情(我的意思是失败了)
好吧,让我们尝试仅定位第一个表(在 [0]之前添加 //th),看看是否可以得到一些东西。
$gettables = $xp->query("//div[contains(@class,'main-wrap')]/table[contains(@class, 'table-wrap')][0]//th", $sp);

不。非对象。长度为0。不知道为什么。好吧,让我们开始吧。
也许试试这个?
//div[contains(@class,'main-wrap')]/table[contains(@class, 'table-wrap')]//th[count(following-sibling::*)]

好的。所以Length =100。必须得到一个 th并进行推断。不是我想要的
也许只是
//th[count(*)]

不。非对象。
也许这个吗?
count(//div[contains(@class,'main-wrap')]/table[contains(@class, 'table-wrap')]//th)

不。更多非对象。
那可能就是我尝试过的例子。
失败(很好,学习)很有趣,但是我想念的是什么?
我的输出...我只想找出每个表中有多少 <th>个。
因此,例如:
foreach ($intropath as $sp) {
$xpath = $xp->query("//actual/working/xpath/for/individual/th");
$thcount = count($getsizes->item(0)); // or something?
echo $thcount . '<br>';

在上面的示例中,将输出

3
5

并且当然会继续进行其他98次迭代。
这可能很愚蠢。我一直在引用这个 cheatsheet以及这个 cheatsheet,并且我已经学到了很多有关XPATH功能的知识,但是这个答案在暗示我。在这一点上,我什至不确定执行我的 foreach ($intropath as $sp) {是否是实现我正在做的事情的正确方法。
任何人都想把我从这个洞里挖出来,这样我就可以继续下一步和/或我的生活了吗?

最佳答案

使用迭代的query()调用计算合格节点。

代码:(Demo

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$xp = new DOMXPath($dom);
foreach ($xp->query("//div[contains(@class,'main-wrap')]/table[contains(@class, 'table-wrap')]//tr") as $node) {
echo $xp->query("th", $node)->length , "\n";
}


输出:

3
5

关于php - 使用XPath计算每个表中的TH数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53055926/

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