使用PHP从JSON响应中提取值

时间:2017-08-08 12:48:36

标签: php json curl

我正在将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.

我该怎么做?

3 个答案:

答案 0 :(得分:4)

您的整个代码都是正确的,您只需在代码中将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"];

答案 1 :(得分:2)

是你的结果变量返回字符串?如果它只返回TRUE或FALSE,请尝试添加此代码

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

答案 2 :(得分:0)

<?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); //<----- I will add this line
//Execute the request
$result = curl_exec($ch);

$values = json_decode($result, true);