CURL替代内置的“;file_get_contents()";作用


CURL alternative to the built-in "file_get_contents()" function

因此,根据我的理解,这应该相当简单,因为我只需要更改原始的fileget内容代码,而脚本的其余部分应该仍然可以工作?我已经注释掉了旧文件的get内容,并在下面添加了curl。

从文件获取内容更改为cURL后,下面的代码不会输出

    //$data = @file_get_contents("http://www.city-data.com/city/".$cityActualURL."-".$stateActualURL.".html");
//$data = file_get_contents("http://www.city-data.com/city/Geneva-Illinois.html");
//Initialize the Curl session
$ch = curl_init();
$url= "http://www.city-data.com/city/".$cityActualURL."-".$stateActualURL.".html";
//echo "$url<br>";
 $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);
  curl_close($ch);
//echo $data;
$details = str_replace("'n", "", $data);
$details = str_replace("'r", "", $details);

$detailsBlock = <<<HTML
~<div style='clear:both;'></div><br/><b>(.*?) on our <a href='http://www.city-data.com/top2/toplists2.html'>top lists</a>: </b><ul style='margin:10px;'>(.*?)<div style='bp_bindex'>~
HTML;
$detailsBlock2 = <<<HTML
~<br/><br/><b>(.*?) on our <a href='http://www.city-data.com/top2/toplists2.html'>top lists</a>: </b><ul style='margin:10px;'>(.*?)</ul></td>~
HTML;
$detailsBlock3 = <<<HTML
~<div style='clear:both;'></div><br/><b>(.*?) on our <a href='http://www.city-data.com/top2/toplists2.html'>top lists</a>: </b><ul style='margin:10px;'>(.*?)</ul></td>~
HTML;
preg_match($detailsBlock, $details, $matches);
preg_match($detailsBlock2, $details, $matches2);
preg_match($detailsBlock3, $details, $matches3);
if (isset($matches[2]))
{
    $facts = "<ul style='margin:10px;'>".$matches[2];
}
elseif (isset($matches2[2]))
{
    $facts = "<ul style='margin:10px;'>".$matches2[2];
}
elseif (isset($matches3[2]))
{
    $facts = "<ul style='margin:10px;'>".$matches3[2];
}
else
{
    $facts = "More Information to Come...";
}

如果你的脚本有问题,你需要调试它。例如:

$data = curl_exec($ch);
var_dump($data); die();

然后你会得到$data的输出。根据输出,你可以进一步决定下一步在哪里查找故障原因。

下面的函数非常有效,只需向它传递一个URL即可。

function file_get_data($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
    curl_setopt($ch, CURLOPT_URL, $url);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

提示:新行和回车可以用一行代码替换。

 $details = str_replace(array("'r'n","'r","'n"), '', $data);