2016-11-13 32 views
0

我想從外部URL獲取元標記。不幸的是,我網站上的meta標籤放在標籤後面。 我使用get_meta_tags($url)但它沒有工作。 這是外部網址來源,我的元標記說明最後存在。PHP獲得meta標記<head>標記

<html><meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
<head><title>Tools</title> 
</head> 
<body><h2>Sitemap Notification Received</h2> 
<br> 
Your Sitemap has been successfully added to our list of Sitemaps to crawl. If this is the first time you are notifying Google about this Sitemap, please add it via <a href="http://www.google.com/webmasters/tools/">http://www.google.com/webmasters/tools/</a> so you can track its status. Please note that we do not add all submitted URLs to our index, and we cannot make any predictions or guarantees about when or if they will appear.</body></html> 
<meta name='description' content='200'> 
+0

你錯過了共享代碼,它增加了meta標籤。 – zyexal

回答

0

這個功能應該可以幫助您:

function file_get_contents_curl($url) 
{ 
    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 

    $data = curl_exec($ch); 
    curl_close($ch); 

    return $data; 
} 

$html = file_get_contents_curl("http://example.com/"); 

//parsing begins here: 
$doc = new DOMDocument(); 
@$doc->loadHTML($html); 
$nodes = $doc->getElementsByTagName('title'); 

//get and display what you need: 
$title = $nodes->item(0)->nodeValue; 

$metas = $doc->getElementsByTagName('meta'); 

for ($i = 0; $i < $metas->length; $i++) 
{ 
    $meta = $metas->item($i); 
    if($meta->getAttribute('name') == 'description') 
     $description = $meta->getAttribute('content'); 
    if($meta->getAttribute('name') == 'keywords') 
     $keywords = $meta->getAttribute('content'); 
} 

echo "Title: $title". '<br/><br/>'; 
echo "Description: $description". '<br/><br/>'; 
echo "Keywords: $keywords"; 

或更容易與此:

<?php 
// Assuming the above tags are at www.example.com 
$tags = get_meta_tags('http://www.example.com/'); 

// Notice how the keys are all lowercase now, and 
// how . was replaced by _ in the key. 
echo $tags['author'];  // name 
echo $tags['keywords'];  // php documentation 
echo $tags['description']; // a php manual 
echo $tags['geo_position']; // 49.33;-86.59 
?>