[英]Get all text within parent node with xpath
I just started using Xpath for a project in PHP. 我刚刚开始将Xpath用于PHP中的项目。 I have to get the individual prices for each product from a website. 我必须从网站上获取每种产品的个别价格。 Each individual product's price info has the following format: 每个产品的价格信息均采用以下格式:
<div class="priceStockDetail">
<dl>
<dt>Across any 6</dt>
<dd><span class='price '><span class='currency'>$</span>20<span class=cents>.90</span></span></dd>
<dt>Each</dt>
<dd><span class='price '><span class='currency'>$</span>22<span class=cents>.00</span></span></dd>
</dl>
</div>
I wish to get only the text after <dt>Each</dt>
as one ("$22.00" for the example above) with an Xpath expression. 我希望仅使用Xpath表达式将<dt>Each</dt>
之后的文本作为一个文本(上面示例中为“ $ 22.00”)。
Any help will be greatly appreciated. 任何帮助将不胜感激。
You could either target each piece element and concatenate, or just target the parent and get the nodeValue. 您可以定位每个片段元素并进行连接,也可以定位父对象并获取nodeValue。 Example: 例:
$dom = new DOMDocument();
$dom->loadHTML($html_string);
$xpath = new DOMXpath($dom);
$data = array();
$products = $xpath->query('//dt');
if($products->length > 0) {
foreach($products as $product) {
$product_name = $product->nodeValue;
// either get individually
// $currency = $xpath->evaluate('string(./following-sibling::dd[1]/span/span[@class="currency"])', $product);
// $price = $xpath->evaluate('string(./following-sibling::dd[1]/span/span[@class="currency"]/following-sibling::text())', $product);
// $cents = $xpath->evaluate('string(./following-sibling::dd[1]/span/span[@class="cents"])', $product);
// $product_price = $currency.$price.$cents;
// or
$product_price = $xpath->evaluate('string(./following-sibling::dd[1]/span)', $product);
$data[] = array(
'product_name' => $product_name,
'product_price' => $product_price,
);
}
}
echo '<pre>';
print_r($data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.