PHP網路爬蟲之抓取meta value
Temperature: 0 °C
最近在研究著如何抓取網頁中的meta值...
php中的get_meta_tags函式可以抓取meta name 範例如下...
$tags = get_meta_tags('http://www.example.com/');
echo $tags['author']; // name
echo $tags['keywords']; // php documentation
echo $tags['description']; // a php manual
echo $tags['generator']; // 49.33;-86.59
但無法抓取 open graph 接著我找到另一個範例寫著
$sites_html = file_get_contents('http://www.example.com/');
$html = new DOMDocument();
@$html->loadHTML($sites_html);
$meta_og_img = null;
$meta_og_title = null;
//Get all meta tags and loop through them.
foreach($html->getElementsByTagName('meta') as $meta) {
//If the property attribute of the meta tag is og:image
if($meta->getAttribute('property')=='og:image'){
//Assign the value from content attribute to $meta_og_img
$meta_og_img = $meta->getAttribute('content');
}
if($meta->getAttribute('property')=='og:title'){
//Assign the value from content attribute to $meta_og_title
$meta_og_title = $meta->getAttribute('content');
}
}
echo '<img src=' . $meta_og_img . ' /> <br/>';
echo $meta_og_title ;
但目前仍無法得到想要的結果...怪....
研究中....