php file_get_contents或curl无法正常工作

时间:2011-08-03 07:51:03

标签: php curl

我想通过使用curl从bseindia.com获取数据,但我只获得null作为数据..

这是我的卷曲功能代码:

    <?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);

???

2 个答案:

答案 0 :(得分: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;
    }

例如我使用此功能进行后期操作

答案 1 :(得分: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'])))));