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

PHP with DOMXPath - Sum values after selection of items

我有这个 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>

我只想 select 'open' 的项目,所以我这样做:

$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']");

现在,如果我没记错的话,我们已经分离出了我们想要的 'open' 项。现在,我需要获取 'length' 值,然后 将它们相加得到总长度 以便我可以回显它。我花了几个小时尝试不同的解决方案和研究,但我没有发现任何类似的东西。你们能帮忙吗?

提前致谢。

已编辑 div 错误,抱歉。

我不确定您的意思是所有计算都在 xsl 中完成,还是您只是希望在 php 中可以使用长度总和,但是这捕获并对长度求和。正如@Chris85 在评论中指出的那样 - html 无效 - 每个条目中都有备用的关闭 div 标签 ~ 大概图像应该是 child of div.status?如果是这样,则在尝试定位正确的 parent 时,以下内容将需要稍作修改。也就是说,我在解析它时没有收到来自 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;