0

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?

4 Answers 4

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can return them as an array:

return array(
    'img'  => $img,
    'url'    => $url
);

Comments

0

There are different ways:

  • return them to caller (as an array)
  • declare them outside the function in a different scope optic
  • declare them globals
  • so on

Consider the solution that fit better to your goal.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.