2011-08-03 91 views
0

我想通過使用curl擺脫bseindia.com數據,但我只得到空數據..PHP的file_get_contents或捲曲不工作

這裏是我的捲曲功能代碼:

<?php 
    function load($url, $ispost=0, $data='', $header=array()){ 
     if($url=='' || ($ispost && $data=='')) return; 

     $host=parse_url($url, PHP_URL_HOST); 

     $header[]='User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20100101 Firefox/6.0'; 
     $header[]='Host: '.$host; 
     $header[]='Connection: keep-alive'; 
     $header[]='Referer: http://'.$host.'/'; 
     if($ispost) $header[]='Content-length: '.strlen($data); 

     $ch = curl_init("$url"); 
     if($ispost){ 
      curl_setopt($ch, CURLOPT_POST, 1); 
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
     } 
     curl_setopt($ch, CURLOPT_HEADER, 0); 
     curl_setopt($ch, CURLOPT_VERBOSE, 0); 
     curl_setopt($ch, CURLOPT_FAILONERROR, 1); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 

     $file = curl_exec($ch); 
     $header = curl_getinfo($ch); 
     curl_close($ch); 

     return array('http_code'=>$header['http_code'], 'output'=>$file); 
} 
    ?> 

和這裏的我的電話:

<?php 
    $data = load('http://www.bseindia.com/', 0, ''); 
    if($data['http_code']!==200) exit(json_encode(array('err'=>true, 'msg'=>'Unable to get! Error='.$data['http_code']))); 
    exit(json_encode(array('err'=>false, 'msg'=>json_decode($data['output'])))); 
?> 

,但我在JSON輸出是:

{"err":false,"msg":null} 

但如果我改變

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); 

然後我正在直接印刷,但不被存儲在變量輸出,爲什麼?

所以,我的問題是如何獲取數據,而無需使用:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); 

???

+0

是否有可能與您關閉標題('CURLOPT_HEADER,0'),但仍然要求它們('curl_getinfo')有關? – OverZealous

+0

@OverZealous:但它的工作其他網站,如:google.com ... –

+0

似乎'json_decode($ data ['output'])'返回NULL。該網站是否返回有效的* JSON數據? –

回答

0

我記得我得到相同的結果,其輸出結果和我解決它讓輸出緩衝:

ob_start(); 
// do the functions 
$result = ob_get_contents(); 
ob_end_clean(); 

好運

編輯:

function getUrl($url, $params) 
    { 
     ob_start(); 
     $ch = curl_init($url); 
     curl_setopt($ch, CURLOPT_POST, 1); 
     curl_setopt($ch, CURLOPT_POSTFIELDS, $params); 
     curl_exec($ch); 
     curl_close($ch); 
     $output = ob_get_contents(); 
     ob_end_clean(); 
     return $output; 
    } 

例如我使用此功能做一個事後動作

+0

無法正常工作...您可以使用您的黑客更新我的加載函數並將其發佈在此? ? –

+0

如果你打算使用輸出緩衝來實現,使用'$ result = ob_get_clean()'而不是像這樣嵌套輸出緩衝區。 – adlawson

+0

看我的版;) – ZiTAL

0
if($data['http_code']!==200) 
    exit(json_encode(array('err'=>true, 'msg'=>'Unable to get! Error='.$data['http_code']))); 
exit(json_encode(array('err'=>false, 'msg'=>json_encode(utf8_encode($data['output']))))); 
+0

你需要用utf8_encode解析爲utf8的結果; curl;) – ZiTAL