2015-12-04 37 views
0

获取图像的src在我的HTML我有这个<link rel="image_src" href="data/20/1.jpg" />从html元素

我需要找回的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']; 

有什么建议?

+1

能否请你告诉输入的实例和输出应该怎么样子的呢? – uruloke

回答

1

我认为你只是一个小错误:

您尝试访问$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');