dnn
dnn

Reputation: 57

Get part of contents from another url using PHP

I'm trying to make a script which displays a random drink recipe every time it's run.

I found several sites which have this and displays a random recipe when the page is refreshed, but some of them takes 3-4 seconds to load, and I'm trying to avoid that.

So I found this site: http://www.shotdrinks.com/p/recipes/ ...which doesn't have a "show random recipe"-feature. However, every recipe on this site is numbered, so they can be "called" by adding any number between 1 and 11000 at the end of the url. Fx. http://www.shotdrinks.com/p/recipes/4000.

As such, I'm using this code to display a random recipe every time it runs:

$min=1;
$max=11000;
$number=rand($min,$max);
$link = file_get_html("http://www.shotdrinks.com/p/recipes/$number");

However, this displays the full page, with menu etc. I only need the header, glass type, ingredients and mixing directions. These are in different divs, fx. the ingredients are in a div id called 'rIngredients'. So I tried this, to "isolate" the div:

$link = file_get_contents("http://www.shotdrinks.com/p/recipes/$number");
$file = strip_tags($link, "<div>");
preg_match_all("#<div class=\"rIngredients\">(?:[^<]*)<\/div>#i", $file, $content);
print_r($content); 

But I can't get this to work, it just outputs an empty array.

What am I doing wrong? And is this the "right" way to do something like this?

Upvotes: 1

Views: 150

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173642

You can use DOMDocument in this way:

$doc = new DOMDocument;
$doc->loadHTMLFile('http://example.org/path/to/data');

$ingredients = $doc->getElementsByClassName('rIngredients');

echo $doc->saveHTML($ingredients);

The optional argument to ->saveHTML() has been added since 5.3.6; an alternative is to use ->saveXML($ingredients).

Upvotes: 2

Related Questions