2011-05-24 92 views
0

我有一個問題 - 解析器不解析。這是行不通的!它不會給任何回報!那麼,我想回到一些東西 - 並將結果存儲在一個mysql數據庫中。PHP file_get_contents()和查詢字符串

<?PHP 
// Original PHP code by Chirp Internet: http://www.chirp.com.au 
// Please acknowledge use of this code by including this header. 

$url = "http://www.edi.admin.ch/esv/00475/00698/index.html?lang=de"; 

//$input = @file_get_contents($url) or die("Could not access file: $url"); 

$input = file_get_contents($url) or die("Could not access file: $url"); 

$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; 
if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) 
{ 
    foreach($matches as $match) 
    { 
     // $match[2] = all the data i want to collect... 
     // $match[3] = text that i need to collect - see a detail-page 
    } 
} 
?> 

它有點過頭了:它不回報任何結果。我是否必須將file_get_contents()與查詢字符串一起使用?

+0

您確定使用file_get_contents從url獲取了某些內容嗎? – 2011-05-24 21:06:07

+1

請說出它的作用。不工作不是一個問題。 – 2011-05-24 21:07:57

+0

請參閱[this](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)解析HTML與正則表達式的答案。 – rid 2011-05-24 21:16:43

回答

3

你正在做的事情,你不應該–解析與正則表達式的HTML。不要這樣做!

改爲使用DOM解析函數。 PHP的DOMDocument類是比正則表達式很容易使用,而且更加清晰(穩定):

$dom = new DOMDocument; 
$dom->loadHTML($yourHTML); 

$links = $dom->getElementsByTagName('a'); 

$hrefs = array(); 
foreach ($links as $link) { 
    $hrefs[] = $link->getAttribute('href'); 
} 

獲取其他數據,如文本內容或其他屬性的名稱,是很輕鬆,如果你想這樣做。

4

在這裏工作罰款:

$url = "http://www.edi.admin.ch/esv/00475/00698/index.html?lang=de"; 

$doc = new DOMDocument(); 
// Supress warnings for screwy HTML 
@$doc->loadHTMLFile($url); 

// Use DOM functionality to get all links 
$link_list = $doc->getElementsByTagName('a'); 

$links = array(); 
foreach($link_list as $link) { 
    if($link->getAttribute('href')) { 
    // and put their href attributes and 
    // text content in an array 
    $link_info['href'] = $link->getAttribute('href'); 
    $link_info['text'] = $link->nodeValue; 
    $links[] = $link_info; 
    } 
} 

print_r($links); 

輸出:

Array 
(
    [0] => Array 
     (
      [href] => #webNavigationDiv 
      [text] => Direkt zur Navigation [Alt + 1] 
     ) 

    [1] => Array 
     (
      [href] => #contentStart 
      [text] => Direkt zum Inhalt [Alt + 2] 
     ) 

    [2] => Array 
     (
      [href] => #keywords_fast 
      [text] => Direkt zur Suche [Alt + 5] 
     )