Extracting values ββfrom JSON response using PHP
I am sending JSON data to url and then I receive JSON.
I am using PHP CURL to get data and show it on my page.
My problem is that I can get the json completely and I cannot show only the selected value from the JSON data.
I got this already:
//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"];
My result: {"value":"U heeft Gideon lol gestuurd."}
I only like to have this: U heeft Gideon lol gestuurd.
How can i do this?
+3
source to share
3 answers
All your code is correct, you need to add CURLOPT_RETURNTRANSFER
in true
to your code. Another wise result would not be stored in a variable. And output to screen directly
<?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"];
+4
source to share
<?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);
0
source to share