M
M
Mike Evstropov2015-10-14 03:09:32
PHP
Mike Evstropov, 2015-10-14 03:09:32

PHP Curl Chunked How to write result to variable?

Hello!
Please tell me why the callback does not write the result to the $server_output variable.
Thanks for any help!

// ...
  $response = getCurl($link, $headers, true);
  function getCurl($link, $headers, $chunked = false){
    if(!isset($link) || !isset($headers))
      { print 'Error: getCurl argument'; die(); };
    $server_output = '';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $link);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    if($chunked){
      curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $str){
        $server_output .= $str;
        // на этой строчке $server_output имеет только один последний чанк
        return strlen($str);
      });
      // на этой строчке $server_output уже пуста
      curl_exec($ch);
    }else{
      $server_output = curl_exec($ch);
    };
    curl_close($ch); return $server_output;
  };

and, if you move the callback into a separate function, it also does not write anything:
function getCurl($link, $headers, $chunked = false){
    if(!isset($link) || !isset($headers))
      { print 'Error: getCurl argument'; die(); };
    $server_output = '';
    $callback = function($ch, $str){
      $server_output .= $str;
      return strlen($str);
    };
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $link);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    if($chunked){
      curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
      curl_exec($ch);
    }else{
      $server_output = curl_exec($ch);
    };
    curl_close($ch); return $server_output;
  };

Answer the question

In order to leave comments, you need to log in

2 answer(s)
X
xmoonlight, 2015-10-14
@Aroused

Попробуйте заменить на

global $server_output;
$GLOBALS["server_output"].=$str;

PS: для использования 'use' (и анонимных функций) необходимо PHP >=5.3.0

Вячеслав Барсуков, 2015-10-14
@slavabars

curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $str) use ($server_output){

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question