![](/img/trans.png)
[英]PHP: file_get_contents & curl not working (but terminal curl does)
[英]php file_get_contents or curl not working
我想使用curl从bseindia.com获取数据,但是我只获取null作为数据。
这是我的curl函数代码:
<?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);
???
我记得我得到了相同的结果,它输出了结果,我解析得到了输出缓冲区:
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;
}
例如我使用此功能进行后期操作
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'])))));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.