Getting a specific value from an array - php

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

Related

How to extract and access data from JSON with PHP when some data changes?

I am trying to bring in some API data to a directory in wordpress.
The data I am trying to get is just crypto coin price, none of the other information but because its format is sort of nested (?) it doesnt seem to work.
{
"bitcoin": {
"usd": 16808.82
}
}
This is my code so far:
<?php
$handle = curl_init();
$url = get_post_meta($entity-\>post()-\>ID, '\_drts_field_004', true);
// Set the url
curl_setopt($handle, CURLOPT_URL, $url);
// Set the result output to be a string.
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($handle);
curl_close($handle);
$data = json_decode($output);
echo $output;
var_dump($data);
The results are:
{
"bitcoin":{
"usd":16833.02
}
}
object(stdClass)#10399 (1) {
["bitcoin"]=> object(stdClass)#10492 (1) {
["usd"]=> float(16833.02)
}
}
In this example I am only after the 16833.02
I am trying to do this for lots of different coins, the "usd" will always be the same but the "bitcoin" will change when other coins.
How can I echo only the number?
I have tried lots of variations of echo but cannot get it? Is it possible to do something like:
echo $data['bitcoin']['usd'];
but rather than bitcoin use * ?
As in anything can be there?
You can access the usd value by decoding the JSON to an array instead of an object like this
$data = json_decode($output, true);
$usd = current($data)['usd'];

How to put URL string in json Viber API php

I am a newbie developer trying to learn web development. I am currently working on this project where articles from a website get shared automatically to a viber public chat. I am facing this problem where I cannot put the URL in the media. I think this is because its json. I am not sure what I am doing wrong here. I have included.
<?php
$Tid = "-1";
if (isset($_GET['id'])) {
$Tid = $_GET['id'];
}
$url = 'https://chatapi.viber.com/pa/post';
$jsonData='{
"auth_token":"4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813",
"from": "K9/C2Vz12r+afcwZaexiCg==",
"type":"url",
"media": "$thisID"
// I want to use $thisID as shown above. But when I
do so this error appears [ {"status":3,"status_message":"'media' field value is not a valid url."} ]
// When I use any full form url like https://google.com it works fine
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
?>
This would work as you are using a single quoted literal.
"media": "' . $thisID . '"
But you are always better to make a PHP array or Object and then use json_encode() to create the JSON String like this
$obj = new stdClass;
$obj->auth_token = "4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813";
$obj->from = "K9/C2Vz12r+afcwZaexiCg==";
$obj->type = 'url';
$obj->media = $thisID;
$jsondata = json_encode($obj);
RESULT of echo $jsondata;
{"auth_token":"4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813",
"from":"K9\/C2Vz12r+afcwZaexiCg==",
"type":"url",
"media":"-1"
}

How to get access the properties in this json response?

I am executing a curl request and get a response which returns a json response. Below is the code after the response is sent back.
Response: "Zeros Replaced real token"
{"success":true,"result":{"token":"000000000","serverTime":1471365111,"expireTime":1471365411}}1
Code Used (For Testing) and accessing property:
$json = json_decode($result);
print_r($json); // Prints the Json Response
$firsttry = $json->result['token']; //Access Property results in error :Trying to get property of non-object
$secondtry = $json['token'];
echo $firsttry.'<br>';//Code can't continue because of error from $firsttry.
print_r( $secondtry.'<br>');//Nothing Prints at all
I did notice a weird anomaly where it prints a 1 at the end, where as if i do
json_encode($json);
The return response replaces the one at the end of the string with a "true"
Could the "1 or true" at the end be throwing of the json decode?
Maybe I am missing something simple?
As Requested full test code
$url = "https://website.com/restapi.php";
//username of the user who is to logged in.
$userName="adminuser"; //not real user
$fields_string; //global var
$fields = array( //array will have more in the future
'username' => urlencode($userName)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { global $fields_string;
$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.'?'.$fields_string.'operation=getchallenge');
curl_setopt($ch,CURLOPT_POST, count($fields));
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
json_decode(), by default makes child objects into stdClass objects rather than arrays unless they are explicitly arrays.
Try something like:
$firsttry = $json->result->token;
The var_dump shows you the data type. Since result itself is an object, access its token with -> rather than []
$response = '{"success":true...}'
$json = json_decode($response); //var_dumping this will show you it's an object
echo $json->result->token; // 000000000
I figured out the issue. In the Curl Options I did not have
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
Once i put this in #GentelmanMax solution worked for me, but the issue was in the curl response responding directly, where as the return transfer sends back a string that php can work with, which then allowed json_decode()to function as is should. I knew it was something simple.

Problems parsing JSON with PHP (CURL)

I am trying to access the value for one of the currencies (e.g. GBP) within the "rates" object of the following JSON file:
JSON file:
{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}
This was my approach:
PHP (CURL):
$url = ...
// initialize CURL:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// get the (still encoded) JSON data:
$json = curl_exec($ch);
curl_close($ch);
// store decoded JSON Response in array
$exchangeRates = (array) json_decode($json);
// access parsed json
echo $exchangeRates['rates']['GBP'];
but it did not work.
Now, when I try to access the "timestamp" value of the JSON file like this:
echo $exchangeRates['timestamp'];
it works fine.
Any ideas?
Try removing (array) in front of json_decode and adding true in second parameter
Here is the solution.
$exchangeRates = (array) json_decode($json,TRUE);
https://ideone.com/LFbvUF
What all you have to do is use the second parameter of json_decode function.
This is the complete code snippet.
<?php
$json='{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}';
$exchangeRates = (array) json_decode($json,TRUE);
echo $exchangeRates["rates"]["GBP"];
?>

Getting JSON Object by calling a URL with parameters in PHP

I'm trying to get json data by calling moodle url:
https://<moodledomain>/login/token.php?username=test1&password=Test1&service=moodle_mobile_app
the response format of moodle system is like this:
{"token":"a2063623aa3244a19101e28644ad3004"}
The result I tried to process with PHP:
if ( isset($_POST['username']) && isset($_POST['password']) ){
// test1 Test1
// request for a 'token' via moodle url
$json_url = "https://<moodledomain>/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$obj = json_decode($json_url);
print $obj->{'token'}; // should print the value of 'token'
} else {
echo "Username or Password was wrong, please try again!";
}
Result is: undefined
Now the question:
How can I process the json response format of moodle system? Any idea would be great.
[UPDATE]:
I have used another approach via curl and changed in php.ini following lines: *extension=php_openssl.dll*, *allow_url_include = On*, but now there is an error: Notice: Trying to get property of non-object. Here is the updated code:
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$moodle = "https://<moodledomain>/moodle/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$result = curl($moodle);
echo $result->{"token"}; // print the value of 'token'
Can anyone advise me?
json_decode() expects a string, not a URL. You're trying to decode that url (and json_decode() will NOT do an http request to fetch the url's contents for you).
You have to fetch the json data yourself:
$json = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};

Categories