PHP with 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>

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

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

现在,如果我没记错的话,我们已经隔离了我们想要的"开放"项目。现在,我需要获取"长度"值,并将它们相加以总长度,以便我可以回显它。我花了几个小时尝试不同的解决方案和研究,但我没有找到类似的东西。你们能帮忙吗?

提前谢谢。

编辑了错误的div,对不起。

我不确定你的意思是要在 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;