2011-05-24 44 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] 
     )