simple htmldom parser not parsing microdata

2020-05-07 07:04发布

问题:

I am trying to parse the price $30 from the below microdata :

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

here is the code I am trying to,but its throwing error Fatal error: Call to a member function find()

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

any suggestions, where its going wrong?, or not sure how to parse with

回答1:

You forgot calling the str_get_html(YOUR_HTML) function? or file_get_html(YOUR_FILE)

If you didn't forget it, then probablt the missing single quotes in attribute values was the problem: itemprop='price'

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

For a single product:

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

For all products:

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


回答2:

You need to load the html into the simple-html-dom parser first. At the moment, your string is "http://www.somesite.com" -- not an actual page.

$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>