Reputation: 1631
I'm using simple html DOM and extracting two links from website.
function get_links($website) {
$html = file_get_html($website);
$img = $html->find('div.entry img',0)->src;
$url = $html->find('div.entry a',0)->href;}
how do I use $img and $url after I run function get_links?
Upvotes: 0
Views: 107
Reputation: 238115
You have two options. The first is to return them:
function get_links($website) {
$html = file_get_html($website);
$img = $html->find('div.entry img',0)->src;
$url = $html->find('div.entry a',0)->href;
return array('img' => $img, 'url' => $url);
}
You can only return one value from a function, so you have to make an array.
The other option is to take arguments by reference:
function get_links($website, &$img, &$url) {
$html = file_get_html($website);
$img = $html->find('div.entry img',0)->src;
$url = $html->find('div.entry a',0)->href;
}
When you call this, you can then provide two values, which will contain the values:
get_links($someurl, $image, $url);
echo $image; // echoes the image source
echo $url; // echoes the url
I expect the first technique (the array) would be the simpler.
You have other options: you could make $img
and $url
global. This is a Bad Idea. You could also define get_links
as an anonymous function and use the use
keyword, but this is less useful, I think. You could also encapsulate the function in an object:
class Links {
public $url;
public $img;
function __construct($website)
$html = file_get_html($website);
$this->img = $html->find('div.entry img',0)->src;
$this->url = $html->find('div.entry a',0)->href;
}
}
// elsewhere
$links = new Links($someurl);
$links->img;
$links->url;
}
Upvotes: 4
Reputation: 24579
Your function is only partially complete. You need to return those values to the calling origin for use there. When returning multiple values from a function, I prefer to return it as an associative array.
function get_links($website) {
$html = file_get_html($website);
$img = $html->find('div.entry img',0)->src;
$url = $html->find('div.entry a',0)->href;}
$results = array('img' => $img, 'url' => $url);
return $results;
}
Upvotes: 0
Reputation: 29932
There are different ways:
Consider the solution that fit better to your goal.
Upvotes: 0
Reputation: 160963
You can return them as an array:
return array(
'img' => $img,
'url' => $url
);
Upvotes: 1