2013-01-20 115 views
0

我試圖從Facebook上鍊接頁面。但是,我得到一個空白頁面,沒有任何錯誤消息。試圖從網頁上刮掉所有的Facebook鏈接

我的代碼如下:

<?php 
error_reporting(E_ALL); 

function getFacebook($html) { 

    $matches = array(); 
    if (preg_match('~^https?://(?:www\.)?facebook.com/(.+)/?$~', $html, $matches)) { 
     print_r($matches); 

    } 
} 

$html = file_get_contents('http://curvywriter.info/contact-me/'); 

getFacebook($html); 

這有什麼錯呢?

+1

這有什麼錯呢? –

+0

得到一個空白頁..沒有輸出.. –

+0

這意味着你的比賽失敗。嘗試'preg_match_all',一次,並從你的模式中剔除'^'和'$'。 –

回答

1

一個更好的選擇(更強大的)是使用DOM文檔和DOMXPath:

<?php 
error_reporting(E_ALL); 

function getFacebook($html) { 

    $dom = new DOMDocument; 
    @$dom->loadHTML($html); 

    $query = new DOMXPath($dom); 

    $result = $query->evaluate("(//a|//A)[contains(@href, 'facebook.com')]"); 

    $return = array(); 

    foreach ($result as $element) { 
     /** @var $element DOMElement */ 
     $return[] = $element->getAttribute('href'); 
    } 

    return $return; 

} 

$html = file_get_contents('http://curvywriter.info/contact-me/'); 

var_dump(getFacebook($html)); 

爲了您的具體問題,但是,我做了以下幾件事:

  • 變化preg_matchpreg_match_all,以便在首次發現後不會停止。
  • 刪除模式中的^(開始)和$(結束)字符。您的鏈接將出現在文件的中間,而不是在開始或結束(絕對不是兩個!)

所以糾正代碼:

<?php 
error_reporting(E_ALL); 

function getFacebook($html) { 

    $matches = array(); 
    if (preg_match_all('~https?://(?:www\.)?facebook.com/(.+)/?~', $html, $matches)) { 
     print_r($matches); 

    } 
} 

$html = file_get_contents('http://curvywriter.info/contact-me/'); 

getFacebook($html); 
+0

你能指出我在正確的方向如何我可以清除代碼並刪除額外的標籤,如'taget =空白'和錨文本。我只想要Facebook的網址。 –