我将JSON数据发送到URL,然后我也收到了JSON.
我正在使用PHP CURL来接收数据并在我的页面上显示它.
我的问题是我只能完全获得json,而且我不能只显示该JSON数据中的选定值.
我已经得到了这个:
//API Url
$url = "https://auth.unilinxx.com/test";
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array("value" => "Gideon lol");
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
//Execute the request
$result = curl_exec($ch);
$values = json_decode($result, true);
echo $values["value"];
我的结果是:{“value”:“U heeft Gideon lol gestuurd.”}
我喜欢只有这个:U heeft Gideon lol gestuurd.
我怎样才能做到这一点?
解决方法:
您的整个代码都是正确的,只需在代码中将CURLOPT_RETURNTRANSFER添加为true即可.其他明智的结果不会存储在变量中.并直接输出到屏幕
<?PHP
//API Url
$url = "https://auth.unilinxx.com/test";
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array("value" => "Gideon lol");
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //<---------- Add this line
//Execute the request
$result = curl_exec($ch);
$values = json_decode($result, true);
echo $values["value"];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。