简单的htmldom解析器不解析微数据

时间:2014-08-23 15:41:10

标签: php simple-html-dom

我试图从下面的微数据中解析价格30美元:

<div itemprop="offers" itemscope="" itemtype="http://schema.org/Offer">
<span itemprop="price"><strong>$30.00</strong></span></div>

这是我正在尝试的代码,但它的抛出错误 致命错误:调用成员函数find()

$url="http://somesite.com";
$html=file_get_html($url);
foreach($html->find('span[itemprop=price]') as $price) 
echo $price;

任何建议,哪里出错?或者不确定如何解析

2 个答案:

答案 0 :(得分:2)

你忘了调用str_get_html(YOUR_HTML)函数了吗? 或file_get_html(YOUR_FILE)

如果你没有忘记它,那么问题是属性值中缺少的单引号是问题所在:itemprop='price'

$html = str_get_html('<div itemprop="offers" itemscope="" itemtype="http://schema.org/Offer"><span itemprop="price"><strong>$30.00</strong></span></div>');

对于单个产品:

echo $html->find("span[itemprop='price'] strong",0)->plaintext;

适用于所有产品:

foreach($html->find("span[itemprop='price'] strong") as $price) {
   echo $price->plaintext."<br/>";
}

答案 1 :(得分:1)

您需要先将html加载到simple-html-dom解析器中。目前,您的字符串是&#34; http://www.somesite.com&#34; - 不是实际页面。

$str = '<div itemprop="offers" itemscope="" itemtype="http://schema.org/Offer">
<span itemprop="price"><strong>$30.00</strong></span></div>';

$html = str_get_html($str);

foreach ($html->find('span[itemprop=price]') as $price) {
    echo $price . "\n";
}

// returns <span itemprop="price"><strong>$30.00</strong></span>