spazhead
spazhead

Reputation: 304

file_get_contents with preg_match receives errors

I am trying to get some data of a website (taste.com.au) but i am not successful at getting data of an element with no class or id.

Here is my code:

$url = "http://www.taste.com.au/recipes/15281/asparagus+with+sun+dried+tomatoes+and+basil";
$html = file_get_contents($url);

This one works:

preg_match("/<h1 itemprop=\"name\">(.*)<\/h1>/i", $html, $title);
echo $title;

Where the html is:

<td class="prepTime">
    <em itemprop="prepTime">0:10</em> //Data i want
    <p>To Prep</p>
</td>

But i am not sure how to get the data of code like this:

<td class="cookTime">
    <em>0:15</em> //Data i want
    <p itemprop="cookTime" datetime="PT15M">To Cook</p>
</td>

**UPDATE: **Im still in need of help, i've tried adding in the start of the tag after it, still doesnt work.

Upvotes: 0

Views: 395

Answers (1)

user1978142
user1978142

Reputation: 7948

Alternatively, you might want to use DOMXPath to traverse and find your desired values. Consider this example:

$url = "http://www.taste.com.au/recipes/15281/asparagus+with+sun+dried+tomatoes+and+basil";
$html = file_get_contents($url);
$dom = new DOMDocument();
@$dom->loadHTML($html);

$finder = new DomXPath($dom);
$values = $finder->query("//tr[@class='info-row']/td[@class='cookTime']/em");

foreach($values as $value) {
    echo $value->nodeValue; // 0:15
}

Upvotes: 1

Related Questions