我正在开发一个 PHP 脚本:
我不知道如何获得curl_exec的最终响应。$response = call('GET', $query) 中的curl_exec; - 即使尚未完成也会返回一些响应。
这些我的循环正在等待调用函数的响应。但它不起作用 json_decode($stringJSON) 在获得最终响应之前被调用
$requestHandled = false;
$response = "";
$response = call('GET', $query);
while(!$requestHandled) {
if(strlen($response) > 5){
$response = mb_convert_encoding($response, "UTF-8");
$stringJSON = get_magic_quotes_gpc() ? stripslashes($response) : $response;
echo $stringJSON;
$jsonObject = "+";
echo $jsonObject;
$jsonObject = json_decode($stringJSON);
echo $jsonObject;
$requestHandled = true;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的curl调用函数
function call($method, $url, $data = false) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $url);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: ' . strlen($data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
return curl_exec($ch);
Run Code Online (Sandbox Code Playgroud)
请帮忙。花了半天解决
那么结果var_dump( $response )是一个空字符串?
在这种情况下,它仅意味着服务器的响应为空,因为我刚刚测试了您的功能call(),它似乎工作得很好。换句话说,请确保您尝试调用的 URL(使用 GET 方法)实际上首先返回数据。
如果您只是在 URL 中的某处出现拼写错误,我不会感到惊讶。
另外,出于调试目的,暂时替换
return curl_exec($ch);
Run Code Online (Sandbox Code Playgroud)
和
$result = curl_exec($ch);
var_dump(curl_getinfo($ch));
return $result;
Run Code Online (Sandbox Code Playgroud)
例如,调查结果中的信息var_dump(),以确保响应代码200(或任何其他指示成功的代码)不在4xx或范围内(分别指示客户端或服务器错误)。5xx
请参阅curl_getinfo()参考资料,了解关于您上次转账将返回哪些有用信息的更多信息curl。
解决OP评论:
请尝试这个完整的脚本(没有别的:无while循环、 no stripslashes()、 nojson_decode()等):
<?php
function call($method, $url, $data = false) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $url);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: ' . strlen($data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
var_dump(curl_getinfo($ch)); // check this result and make sure the response code is 200
return $result;
}
$query = 'fill in the correct URL! (with http(s)://)';
$response = call('GET', $query);
var_dump( $response ); // check this result and see if it's an empty string
die;
Run Code Online (Sandbox Code Playgroud)
如果var_dump( $response );返回空字符串,则意味着您的脚本工作正常,但您调用的 URL 仅返回空响应。
如果$response不为空且实际包含JSON数据,则替换
var_dump( $response );
Run Code Online (Sandbox Code Playgroud)
和
$stringJSON = mb_convert_encoding( $response, "UTF-8" );
echo $stringJSON; // make sure this contains valid JSON data
// stripslashes() should not be needed
var_dump( json_decode( $stringJSON ) ); // if JSON data was valid, you should get a valid PHP data structure
Run Code Online (Sandbox Code Playgroud)