PHP与DOMXPath - 选择项目后的总和值

时间:2016-01-16 14:51:03

标签: php domxpath

我有这个html结构:

<div class="wanted-list">
    <div class="headline"></div>
    <div class="entry">
        <div></div>
        <div></div>
        <div class="length">1100</div>
        <div></div>
        <div class="status">
            <img src="xxxx" alt="open">
        </div>
    </div>
    <div class="entry mark">
        <div></div>
        <div></div>
        <div class="length">800</div>
        <div></div>
        <div class="status">
            <img src="xxxx" alt="open">
        </div>
    </div>
    <div class="entry">
        <div></div>
        <div></div>
        <div class="length">2300</div>
        <div></div>
        <div class="status">
            <img src="xxxx" alt="closed">
        </div>
    </div>
</div>

我只想选择“打开”的项目,所以我这样做:

$doc4 = new DOMDocument();
$doc4->loadHtmlFile('http://www.whatever.com');
$doc4->preserveWhiteSpace = false;
$xpath4 = new DOMXPath($doc4);
$elements4 = $xpath4->query("//div[@class='wanted-list']/div/div[5]/img[@alt='open']");

现在,如果我没有弄错的话,我们已经隔离了“开放式”。我们想要的东西。现在,我需要得到长度&#39;值和将它们相加以使总长度所以我可以回应它。我花了几个小时尝试不同的解决方案和研究,但我还没有找到类似的东西。你们能帮忙吗?

提前致谢。

已编辑错误的div,抱歉。

1 个答案:

答案 0 :(得分:1)

我不确定你是否想要在xsl中完成所有计算,或者你是否只想在php中使用长度总和,但这会捕获并总结长度。正如@ Chris85在评论中指出的那样 - html无效 - 每个条目中都有备用的关闭div标签〜大概是图像应该是div.status的孩子?如果是这样的话,下面的内容在尝试定位正确的父级时需要稍作修改。也就是说,DOMDocument在解析它时没有收到任何警告,但最好修复而不是忽略!

$strhtml='
<div class="wanted-list">
    <div class="headline"></div>
    <div class="entry">
        <div></div>
        <div></div>
        <div class="length">1100</div>
        <div></div>
        <div class="status">
            <img src="xxxx" alt="open">
        </div>
    </div>
    <div class="entry mark">
        <div></div>
        <div></div>
        <div class="length">800</div>
        <div></div>
        <div class="status">
            <img src="xxxx" alt="open">
        </div>
    </div>
    <div class="entry">
        <div></div>
        <div></div>
        <div class="length">2300</div>
        <div></div>
        <div class="status">
            <img src="xxxx" alt="closed">
        </div>
    </div>
</div>';


$dom = new DOMDocument();
$dom->loadHtml( $strhtml );/* alternative to loading a file directly */
$dom->preserveWhiteSpace = false;

$xp = new DOMXPath($dom);               
$col=$xp->query('//img[@alt="open"]');/* target the nodes with the attribute you need to look for */
/* variable to increment with values found from DOM values */
$length=0;

foreach( $col as $n ) {/* loop through the found nodes collection */
    $parent=$n->parentNode->parentNode;/* corrected here to account for change in html layout ~ get the suitable parent node */

    /* based on original code, find value from particular node */
    $length += $parent->childNodes->item(5)->nodeValue; 
}
echo 'Length:'.$length;