【问题标题】:PHP DomDocument query in results结果中的 PHP DomDocument 查询
【发布时间】:2022-01-27 16:08:31
【问题描述】:

昨天我发现了 php DomDocument,我意识到它可以帮助我很多(更快 - 我使用 php 和正则表达式)从 html 获取值。

我被卡住了,我找不到解决方案(可能是我的思维方式) - 现在搜索了 16 多个小时,仍然没有解决方案。

$res = '
<html>
<div class="product bla bla">
<div class="size">xxl</div>
<div class="color yy">red</div>
</div>

<div class="product bla">
<div class="size xxs">xxs</div>
<div class="line line2">new</div>
</div>

<div class="product asd">
<div class="color xx">blue</div>
</div>
</html>
';

$dom = new DomDocument();
@ $dom->loadHTML($res); // utf8_decode
$dom->preserveWhiteSpace = false; // ?
$xpath = new DomXPath($dom);
$nodes = $xpath ->query("//*[contains(@class, 'product')]");

echo "Found {$nodes->length} matching places" . PHP_EOL;

foreach($nodes  as $node) {
    $name = $xpath->query("//*[contains(@class, 'color')]", $node);
    echo "<br>";
    echo $name[0]->nodeValue . PHP_EOL;
}

结果:

Found 3 matching places
red
red
red 

预期结果是:

Found 3 matching places
red
Null / empty or so...
blue

我的问题是如何在搜索结果中搜索(保留索引 ex. [0] - red, [1] - null, 2 - [blue])

另外,如果您知道了解 DomDocument 的好地方,请告诉我

感谢您的帮助或提示。

【问题讨论】:

    标签: php html domdocument domxpath


    【解决方案1】:

    将最后几行修改为:

    foreach($nodes  as $node){
         // do not use `//` as it means "from the root of the document", 
         // and not from the root of the node you provided
         $name = $xpath->query("*[contains(@class, 'color')]", $node);
         // check if name[0] node exists
         echo null === $name[0] ? 'NULL' : $name[0]->nodeValue;
         echo PHP_EOL;
    }
    

    小提琴是here

    【讨论】:

    猜你喜欢
    • 2012-05-06
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2010-11-25
    • 1970-01-01
    • 2011-06-01
    相关资源
    最近更新 更多