使用 PHP 和简单 HTML DOM 解析 HTML 时遇到问题

Having trouble parsing HTML with PHP and Simple HTML DOM

我正在尝试用 simple_html_dom.php 解析 HTML。我正在尝试解析的 HTML 如下所示。我可以成功抓取每个产品名称:Product 1Product 2Product 3

我也想从每个产品中获取 itemprice_0。这就是我 运行 遇到问题的地方。这是我的代码:

<?php
require_once 'simple_html_dom.php';

$html = file_get_html('https://www.webaddress.com');

foreach($html->find('span.productName') as $e)
echo $e.'<br />'; //successfully displays all product names

foreach($html->find('#itemprice_0') as $e)
echo $e; //doesn't display the item prices

foreach($html->find('.dollar') as $e)
echo $e; //doesn't display the dollar amounts
?>

这里是HTML:

<span class="productName">Product 1</span>  

<p class="price">
<strike>
<span class="dollar-symbol">$</span>  
<span class="dollar">15</span><span class="dot">.</span>  
<span class="cents">99</span></strike>
</p>  

<p class="salePrice" id='itemprice_0'>  
<span class="dollar-symbol">$</span>  
<span class="dollar">13</span><span class="dot">.</span>  
<span class="cents">99</span>  
</p>

itemprice_0 是唯一的,如果你想 select 多个元素你应该使用 class select 或者。在 simple_html_dom 中,您可以像这样获取嵌套元素(未测试):

<?php
require_once 'simple_html_dom.php';

foreach($html->find('.salePrice') as $prices){
    echo $price->find('.dollor')->plaintext;
    echo $price->find('.cents')->plaintext;
}

我访问了 salePrice class 并输出了美元金额。

foreach($html->find('span.productName') as $e)
    echo $e.'<br />'; //successfully displays all product names

foreach($html->find('p.price') as $e)
    $e = str_replace(' ', '', $e);
    echo 'Regular Price: ' . $e;

foreach($html->find('p.salePrice') as $e)
    $e = str_replace(' ', '', $e);
    echo 'Sale Price: ' . $e;

我还删除了空格。

结果:

Product 1
Regular Price: .99
Sale Price: .99

我还让循环只查找 itemprice_0 id,得到了相同的结果:

foreach($html->find('p[id=itemprice_0]') as $e)
$e = str_replace(' ', '', $e);
echo 'Sale Price: ' . $e;

同样的结果:

Product 1
Regular Price: .99
Sale Price: .99

这是您要找的吗?

您可以使用以下解决方案来解决您的问题:

$domd=@DOMDocument::loadHTML($html);
$xp=new DOMXPath($domd);
foreach($xp->query('//*[contains(@class,"dollar")]') as $e)
var_dump($e->textContent);