一个虚拟脚本,它响应了一些json ..
<?php
$result['code'] = 200;
echo json_encode($result);
?>
然而,当我对此脚本进行curl调用时,尝试获取json响应然后将其转换为array..things出错。
通常我会做一个简单的json_decode($ json),它会给我一个数组,但显然当我var_dump json_decode($json)
时,它会给我int(1)
作为回应。我只是想从json中获取代码。
这是我的代码:
public function curlcall($username, $msg)
{
$url = 'someurl.php';
$fields = array('username' => $username, 'message' => $msg);
$fields_string = null;
foreach ($fields as $key => $value) {$fields_string .= $key . '=' . $value . '&';}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo '-------------------------';
var_dump($result);
exit;
}
当我从rest客户端直接调用脚本时,它给了我完美的json响应。但是当我通过curl请求相同的json时,在将json转换为数组时,我得不到所需的结果。
为了简单起见,我只是回显了一个字符串,但是当我var_dump
它时,它给了我int(1).
答案 0 :(得分:-1)
试试这个:
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //NOTICE this line, which says you want a response returned to the calling script
$result = curl_exec($ch);
curl_close($ch);
echo '-------------------------';
var_dump($result);