2012-06-15 63 views
0

我寫簡單的3個功能報廢的標題,描述和簡單的HTML 頁面的關鍵字,這是報廢冠軍功能,以廢頁面的關鍵字,描述和標題?

function getPageTitle ($url) 
{ 
    $content = $url; 
    if (eregi("<title>(.*)</title>", $content, $array)) { 
     $title = $array[1]; 
     return $title; 
    } 
} 

第一功能並能正常工作 和那些2個功能報廢描述和關鍵字和那些沒有工作

function getPageKeywords($url) 
{ 
    $content = $url; 
    if (preg_match('/<meta[\s]+[^>]*?name[\s]?=[\s\"\']+keywords[\s\"\']+content[\s]?=[\s\"\']+(.*?)[\"\']+.*?>/i', $content, $array)) { 
     $keywords = $array[1]; 
     return $keywords; 
    } 
} 
function getPageDesc($url) 
{ 
    $content = $url; 
    if (preg_match('/<meta[\s]+[^>]*?name[\s]?=[\s\"\']+description[\s\"\']+content[\s]?=[\s\"\']+(.*?)[\"\']+.*?>/i', $content, $array)) { 
     $desc = $array[1]; 
     return $desc; 
    } 
} 

我知道有可能是用的preg_match線有點問題,但我真的不知道 我嘗試了這麼多的事情,但它不工作

+1

只是說明:'eregi'已棄用。 http://php.net/manual/en/function.eregi.php – Will

+1

使用正則表達式來解析HTML比任何簡單的標籤對更復雜;當你嘗試開始解析標籤屬性時,你需要切換到PHP Dom:http://php.net/manual/en/book.dom.php這裏的概率是名稱,描述和內容屬性必須在您匹配的訂單。 – Sp4cecat

+0

第三個重要的一點,只是因爲它在網頁上並不意味着你有權利使用任何你喜歡的數據(沒有權限) – 2012-06-15 03:40:14

回答

2

爲什麼不使用get_meta_tags? PHP Documentation Here

<?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 
?> 

注意您可以將參數更改爲一個URL,本地文件或字符串。

+0

Thx這是解決它 – Marco

1

它更好地使用PHP的本地DOMDocument來解析HTML然後正則表達式,你也可以使用,在這一天的年齡分配的網站甚至不添加關鍵字,描述標籤沒有更多,所以你不能依靠他們總是在那裏。但這裏是如何使用DOMDocument來做到這一點:

<?php 
$source = file_get_contents('http://php.net'); 

$dom = new DOMDocument("1.0","UTF-8"); 
@$dom->loadHTML($source); 
$dom->preserveWhiteSpace = false; 

//Get Title 
$title = $dom->getElementsByTagName('title')->item(0)->nodeValue; 

$description = ''; 
$keywords = ''; 
foreach($dom->getElementsByTagName('meta') as $metas) { 
    if($metas->getAttribute('name') =='description'){ $description = $metas->getAttribute('content'); } 
    if($metas->getAttribute('name') =='keywords'){ $keywords = $metas->getAttribute('content'); } 
} 

print_r($title); 
print_r($description); 
print_r($keywords); 
?> 
相關問題