Unable to fetch single data from JSON Curl Output in PHP [duplicate] - php

This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How to use cURL to get jSON data and decode the data?
(6 answers)
Closed 10 months ago.
I have a code which should fetch courseID from JSON response obtained , But currently it is not fetching anything . It shows me the entire response and not one . can someone help me with this .
JSON response obtained.
{
"results": [
{
"CourseID": "ASPO",
"Success": "Yes"
}
]
}
i just want to retrieve the CourseID.
and below is my code
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://AbC:3939');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "ABC=AE");
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Authorization: Bearer hjhjhjhjhjhj338sj';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch) ;
}else{
$result_value = json_decode($result);
print_r($result_value->results[0]->CourseID);
}
curl_close($ch);
?>

I have tried this with your shared result and got the COURSEID.
$resp = '{
"results": [
{
"CourseID": "ASPO",
"Success": "Yes"
}
]
}';
$res = json_decode($resp);
print_r($res->results[0]->CourseID);

Note: this answers the original question (extract information from JSON response).
The top level element in your JSON string is an object with a single results key that holds everything. You aren't referencing such key anywhere in your code.
The name of the local PHP variable where you store the results is irrelevant, there isn't any automatic behaviour linked to that.
If you use json_decode() with the $associative flag you get JSON objects converted to PHP arrays (JSON arrays become PHP arrays no matter the flags). If unsure, just inspect your data with either a step debugger or e.g. var_dump($result_value):
array(1) {
'results' =>
array(1) {
[0] =>
array(2) {
'CourseID' =>
string(4) "ASPO"
'Success' =>
string(3) "Yes"
}
}
}
In php you can access array elements by specifying the key inside square brackets so:
var_dump($result_value['results'][0]['CourseID'], $result_value['results'][0]['Success']);
string(4) "ASPO"
string(3) "Yes"

Related

cURL request won't work with data from fetch API

I'm sending some data with the fetch API to a translate.php file, here is my JS code:
const translation = {
word: 'Hello'
};
fetch('http://yandex.local/translate.php', {
method: 'POST',
body: JSON.stringify(translation),
headers: {
'Content-Type': 'application/json'
}
}).then(res => {
return res.text();
}).then(text => {
console.log(text);
})
Here is how I try to get the data on the translate.php:
$postData = json_decode(file_get_contents("php://input"), true);
$word = $postData['word'];
Here is my cURL request:
$word = $postData['word'];
$curl = curl_init();
$request = '{
"texts": "Hello",
"targetLanguageCode": "ru",
"sourceLanguageCode": "en"
}';
curl_setopt($curl, CURLOPT_URL, 'https://translate.api.cloud.yandex.net/translate/v2/translate');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Api-Key 123456",
"Content-Type: application/json"
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
$err = curl_error($curl);
if($err) {
echo 'Curl Error: ' . $err;
} else {
$response = json_decode($result, true);
print_r($response['translations']['0']['text']);
}
curl_close($curl);
When I'm runing this code I get the translation of Hello in russian which is Привет. But if I replace "Hello" in the request object by $word I got the error: Trying to access array offset on value of type null
Here is the way I rewrite the request object:
$request = '{
"texts": $word,
"targetLanguageCode": "ru",
"sourceLanguageCode": "en"
}';
When I check the XHR of my translate.php all seems ok, I have a status 200 and the request payload shows my data. Also the word "hello" displays correctly in the console of my index.php
Don't ever create JSON strings by hand (i.e. I mean by hard-coding the JSON text directly into a string variable). It can lead to all kinds of syntax issues accidentally.
Please replace
$request = '{
"texts": "Hello",
"targetLanguageCode": "ru",
"sourceLanguageCode": "en"
}';
with
$requestObj = array(
"texts" => $word,
"targetLanguageCode" => "ru",
"sourceLanguageCode" => "en"
);
$request = json_encode($requestObj);
This will produce a more reliable output, and also include the $word variable correctly.
P.S. Your actual issue was that in PHP, variables are not interpolated inside a string unless that string is double-quoted (see the manual). Your $request string is single-quoted.
Therefore $word inside your $request string was not changed into "Hello" but left as the literal string "$word". And also since you removed the quotes around it, when the remote server tries to parse that it will not be valid JSON, because a text variable in JSON must have quotes around it. This is exactly the kind of slip-up which is easy to make, and why I say not to build your JSON by hand!
Your version would output
{"texts":$word,"targetLanguageCode":"ru","sourceLanguageCode":"en"}
whereas my version will (correctly) output:
{"texts":"Hello","targetLanguageCode":"ru","sourceLanguageCode":"en"}
(Of course I should add, given the comment thread above, that regardless of my changes, none of this will ever work unless you send a correct POST request to translate.php containing the relevant data to populate $word in the first place.)

Accessing variables of curl response in PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
This is the first time I have used curl, and am confused how exactly the $response is formatted, and how I go about accessing the information I want in it. I am trying to access a particular variable from a curl response in PHP to be used in a future conditional. I was provided the URL, and headers to use as an API endpoint, and thus can't change anything on that end. Here is the code for the curl response :
$ch = curl_init();
$url = "https://thewebsitesurl.com";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'x-branch: 21',
'x-branchhash: fijef89ivjw8934y8f9fifk920a',
'accept: application/json'
));
$response = curl_exec($ch);`
The contents of a var_dump($response) yields :
string(187) "{"code":"5122","time":"1589812650","voucher":{"code":"5122","comments":"","amount":"11.00","balance":"11.00","created":"1589609333","expiry":"1652616000","redeemed":false,"voided":false}}"
I need to access the "redeemed" and "voided" field. Of course this being a big long string means I can't do that (I believe). Is there a CURLOPT I should be setting so the response isn't received as one big string?
Further if I decode it with $data = var_dump(json_decode($result, true)); the contents are :
array(3) { ["code"]=> string(4) "5122" ["time"]=> string(10) "1589814039" ["voucher"]=> array(8) { ["code"]=> string(4) "5122" ["comments"]=> string(0) "" ["amount"]=> string(5) "11.00" ["balance"]=> string(5) "11.00" ["created"]=> string(10) "1589609333" ["expiry"]=> string(10) "1652616000" ["redeemed"]=> bool(false) ["voided"]=> bool(false) } }
To me this seems much more workable than a long string. However I am struggling to access the ["expiry"], ["redeemed'], and ["voided"] variables. In fact I am struggling just to access the ["code"] string "5122" I have tried :
echo $data[0]['code'];
echo $data[0]["code"];
echo $data['code'];
echo $data["code"];
All 4 of those echos are blank. I have tried to remove "curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);" as well. Afterwards var_dump($result); looks like :
{"code":"5122","time":"1589815247","voucher":{"code":"5122","comments":"","amount":"11.00","balance":"11.00","created":"1589609333","expiry":"1652616000","redeemed":false,"voided":false}}bool(true)
I am probably misunderstanding something basic here. But any help would be appreciated on how I could access the values in ["expiry"], ["redeemed'], and ["voided"]. Thank you for your assistance.
$data = json_decode($result, true);
This will return an array
$data = json_decode($result);
This will return an object.
Do not use var_dump inside this because it is a parse function, just for dumping data. So the final should be:
$data = json_decode($result, true);
$code = $data['code']; // " or ' are not different in this case

Getting a specific value from an array

I'm trying to get a specific column from an array for each record returned.
The array is called fields and one of the arrays in the array is locations. I'm looking for a specific column in the array called name.
Here's what I have:
foreach ($new_results as $result):?>
$locations = array_map($result->locations->location,function($obj) { return $obj->location; });
echo implode(",",$locations);
endforeach;
I'm connecting to a web service to pull this data. The above is the code that the company gave me, but they haven't tested it as far as I know. It doesn't work for me.
Here's the call to the API
$results = $connection->call('groups/getAll', $params=array("suspended" => "no","fields" =>"locations"));
$new_results = $results->groups->group;
Here's an example from the API.
{
"id": "xxxx",
"fields": {
"locations": [
"North",
"Central"
]
}
}
Any thoughts on what I'm doing wrong? I'm still very new to PHP so I may be missing something very obvious.
How to get json using curl:
How to get JSON data from Rest API by PHP Curl?
Now with that in mind you can dive a little deeper into the object manipulation in terms of the response here: Accessing JSON object elements in PHP.
//""" code from the first link
$service_url = "http://127.0.0.1:8000/api/thesis/?format=json";
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
//execute the session
$curl_response = curl_exec($curl);
//finish off the session
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);
//""" code from the first link
&
//""" code from the second link
/*Variable passed in from the ExtJS interface as JSON object*/
$json = $_POST["newUserInfo"];
//$json = '{"USER":{"ID":"","FULL_USER_NAME":"Some Guy","ENTERPRISE_USER_NAME":"guyso01","USER_EMAIL":"Some.Guy#Email.com","USER_PHONE":"123-456-7890"},"PERMISSIONS":{"ID":"","USER_ID":"","IS_ADMIN":"true"},"SETTINGS":{"ID":"","USERS_ID":"","BACKGROUND":"default"}}';
//Test to view the decoded output
//var_dump(json_decode($json));
//Decode the $json variable
$jsonDecoded = json_decode($json,true);
//Create arrays for each table from the $jsonDecoded object
$user_info = array($jsonDecoded['USER']);
$permissions_info = array($jsonDecoded['PERMISSIONS']);
$settings_info = array($jsonDecoded['SETTINGS']);
// """ code from the first link

Record the result of a curl GET request using php & mysql

I'm trying to understand how to record the result of a curl GET request using php. I'm looking at outputing part or all of the result to mysql.
https://github.com/cloudtrax/docs/blob/master/api/code/php/simple_api_server_test_harness.php
function invoke_curl($method, $endpoint, $headers, $json) {
$api_server = 'https://api.cloudtrax.com';
try {
// get a curl handle then go to town on it
$ch = curl_init($api_server . $endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if ($result == FALSE) {
if (curl_errno($ch) == 0)
echo "#### NOTE ####: nil HTTP return: This API call appears to be broken" . "\n";
else
throw new Exception(curl_error($ch), curl_errno($ch));
}
else
echo "RESULT: \n" . $result . "\n";
}
The $result shows like this:
{
"clients": {
"ssid2": 4,
"ssid1": 10
},
"rows": [
{
"time": "2016-03-23T02:45:00Z",
"ssid2": {
"traffic": {
"unclassified": {
// etc...
How can I associate each part of the result too a variable so I can then input too mysql?
It looks like this result in json format. You can use json_decode to decode it:
$resultObject = json_decode($result);
$clients = $resultObject->clients;
// ... get other data from result
The code below will convert the json into a PHP array. You can then use the indexes of the array to pull out values.
$result = json_decode($result);
$clients = $result->clients;
// Some MySQL queries
If your response is a JSON response then you can simply use php's json_decode to get parsed object.
$result = curl_exec($ch);
//to get associative array passing true
$jsonObj = json_decode($result, true);
$clients = $jsonObj['clients'];
$rows = $jsonObj['rows'];
You can refer to these answers for more detail:
Parsing JSON object in PHP using json_decode and
Parsing JSON file with PHP

decision making based on json array

I am working on an payment gateway API to process refunds.
On successful operation, the API returns a json array like this
{
"currencyCode" : "GBP",
"amount" : 100,
"originalMerchantRefNum" : "MERCHANTREF12346",
"mode" : "live",
"confirmationNumber" : 1997160616609792,
"authType" : "refund",
"id" : "25TWPTLHRR81AIG1LF"
}
On error the array returned is
{
"error": {
"code": "400",
"message": "Amount exceeds refundable amount"
}
}
I need to decode the json output and then show it to the user. But since the structure of the json array is different in both cases, how do I go arnd parsing the json array, so as to give relevant readable data to the end user.
My code which, does all the talking and fetching data from the gateway processor is given below
<?php
include('lock.php');
$flag=0;
$oid=$_POST['oid'];
if(isset($_POST['amount']))
{
$amount=$_POST['amount'];
$amount = $amount*100;
$flag=1;
}
// generate random number
$merchantref=mt_rand(10,9999999999);
//API Url
$url = 'https://api.netbanx.com/hosted/v1/orders/'.$oid.'/refund';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
if($flag==1)
{
$jsonData = array(
"amount" => $amount,
'merchantRefNum' => $merchantref
);
}
else
{
$jsonData = array(
'merchantRefNum' => $merchantref
);
}
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//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 and HTTP Authorization code
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode("..") //Base 64 encoding and appending Authorization: Basic
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the request
$result = curl_exec($ch);
$jdata=$result;
//decode the json output and store it in a variable
$jfo = json_decode($jdata);
//Handle decision making based on json output
?>
Basically something as simple as:
$response = json_decode(..., true);
if (isset($response['error'])) {
echo 'Sorry, ', $response['error']['message'];
} else {
echo 'Yay!';
}
What exactly you need to check for depends on the possible values the API may return. Most APIs specify something along the lines of "status will be set to 'success' or 'error'", or maybe "if the error key is present, this indicates an error, otherwise a success".

Categories