PHP DomDocument nodeValue返回重复值

时间:2016-03-23 11:37:41

标签: php xpath domdocument

我使用php domdocument和xpath处理非常简单的html代码。我正在获得dom节点的重复值。

PHP代码

<?php

$html = <<<HTML

    <div id="my-cats">

        <ul class="category_list">

            <li class="item reference">
                <span class="the_score"><b>35</b></span>
                <span class="the_category">Reference / Education</span>
            </li>

            <li class="item computer">
                <span class="the_score"><b>50</b></span>
                <span class="the_category">Computer / Internet</span>
            </li>

        </ul>

        <ul class="category_list">

            <li class="item home">
                <span class="the_score"><b>22</b></span>
                <span class="the_category">Home / Gardening</span>
            </li>

            <li class="item home">
                <span class="the_score"><b>12</b></span>
                <span class="the_category">Home / Repair</span>
            </li>

        </ul>

    </div>

HTML;

$dom = new DOMDocument();
@$dom->loadHTML($html);

$finder = new DOMXPath($dom);

$cats = $finder->query('//div[@id="my-cats"]//ul[@class="category_list"]//li');

foreach( $cats as $li ){
    echo $li->getAttribute('class') . "\n";
    $value = trim($finder->query('//span[@class="the_score"]', $li)->item(0)->nodeValue);
    $key = trim($finder->query('//span[@class="the_category"]', $li)->item(0)->nodeValue);
    echo "$key : $value\n";
}

输出

item reference 
Reference / Education : 35 

item computer 
Reference / Education : 35 

item home 
Reference / Education : 35 

item home 
Reference / Education : 35

正如您所看到的,我正在回显显示我正在处理的$li元素的类名称是不同的。但我只获得dom节点的第一个值。

您可以在此处查看问题https://3v4l.org/tjJB5

1 个答案:

答案 0 :(得分:1)

将内部查询更改为例如$finder->query('span[@class="the_score"]', $li)来搜索span的{​​{1}}个孩子。