从html元素中获取图像src


Get image src from html element

在我的HTML中,我有这个<link rel="image_src" href="data/20/1.jpg" />

我需要检索href(data/20/1.jpg)。

我尝试了下面的代码,没有任何运气

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'];

有什么建议吗?

我想你只是犯了一个小错误:

您尝试访问$og['image_src'];,但您的数组没有索引image_src,因为image_src替换为''

您必须替换此行:

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

使用此:

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