2012-09-21 63 views
0

我在我的代码中有一段使用file_get_contents从给定网页抓取url。我的代码中还有一段代码,用于扫描数组中每个链接值的标题。 我想结束了具有类似于这样的数组:file_get_contents不保存到数组

Array(
    Google => array(
    [title] => Google 
    [link] => http://www.google.com 
) 
) 

但没有值保存到我的阵列,即使我不能检测到任何错误

$links = Array(); 

$URL = 'http://www.theqlick.com'; // change it for urls to grab 
$file = file_get_contents($URL); 
// grabs the urls from URL 
if(strlen($file)>0) { 
    $links[] = preg_match_all("/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/", $file, $links); 
} 

function Titles() { 
    global $links; 
    $str = implode('',array_map('file_get_contents',$links)); 
    error_reporting(E_ERROR | E_PARSE); 

    $titles = Array(); 
    if(strlen($str)>0) { 
     $titles[] = preg_match_all("/\<title\>(.*)\<\/title\>/", $str, $title); 
     return $title; 
     return $links; 
    } 
} 
$newArray = array(); 

$j = 0; 

foreach($links as $key => $val){ 
    $newArray[$key] = array('link' => $val, 'title' => $title[1][$j++]); 
} 

print_r($newArray); 
+1

不分配'preg_match_all'的返回值,这不是它是如何工作的。当你不在任何地方调用它时,这里的'Titles'函数在做什么?为什么它有两个'return'语句? – DCoder

回答

0

似乎下面的代码不返回任何东西

$links[] = preg_match_all("/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/", $file, $links); 

请尝试以下

$links = Array(); 

$URL = 'http://www.theqlick.com'; // change it for urls to grab 
$file = file_get_contents($URL); 
// grabs the urls from URL 
if (strlen($file) > 0) { 
    $links[] = preg_match_all('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $file, $links); 
} 

var_dump($links); 

输出

array 
    0 => 
    array 
     0 => string 'http://www.w3.org/TR/xhtmll/DTD/xhtmll-transitional.dtd' (length=55) 
     1 => string 'http://www.w3.org/1999/xhtml' (length=28) 
     2 => string 'http://www.theqlick.com' (length=23) 
     3 => string 'http://www.theqlick.com' (length=23) 
    1 => 
    array 
     0 => string 'd' (length=1) 
     1 => string 'l' (length=1) 
     2 => string 'm' (length=1) 
     3 => string 'm' (length=1) 
    2 => int 4