php file_get_contents или curl не работает - PullRequest
0 голосов
/ 03 августа 2011

Я хочу получить данные с bseindia.com с помощью curl, но в качестве данных я получаю только ноль ..

вот мой код функции 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);
* * ??? 1 022

Ответы [ 2 ]

0 голосов
/ 03 августа 2011
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 голосов
/ 03 августа 2011

я помню, что получаю тот же результат, он выводит результат, и я разрешаю его, получая буфер вывода:

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

удачи

edit:

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;
    }

например, я использую эту функцию, чтобы выполнить действие после публикации

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...