简体   繁体   中英

Get all text within parent node with xpath

I just started using Xpath for a project in 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.

Any help will be greatly appreciated.

You could either target each piece element and concatenate, or just target the parent and get the 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);

Sample Output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM