Search code examples
phppreg-matchsimple-html-dom

Get image src from html element


Inside my HTML I have this <link rel="image_src" href="data/20/1.jpg" />

I need to retrieve the href (data/20/1.jpg).

I tried the code below without any luck

function fetch_rel($url)
{
    $data = file_get_contents($url);
    $dom = new DomDocument;
    @$dom->loadHTML($data);

    $xpath = new DOMXPath($dom);
    # query metatags with og prefix
    $metas = $xpath->query('//*/link[starts-with(@rel, \'image_src\')]');

    $og = array();

    foreach($metas as $meta){
        # get property name without og: prefix
        $property = str_replace('image_src', '', $meta->getAttribute('rel'));
        # get content
        $content = $meta->getAttribute('href');
        $og[$property] = $content;
    }

    return $og;
}
$og = fetch_rel($u);
$image_src = $og['image_src'];

Any suggestions?


Solution

  • I think you've made just a little error:

    You try to access $og['image_src'];, but your array has no index image_src, because you replaced image_src with ''.

    You have to replace this line:

    # get property name without og: prefix <-- By the way: you have no og: prefix ;)
    $property = str_replace('image_src', '', $meta->getAttribute('rel'));
    

    with this:

    $property = $meta->getAttribute('rel');