How to parse JSON with PHP - php

I need help with something..
How can I parse data in this format: https://api.coinmarketcap.com/v1/ticker/
I tried set up a code in php
$url = 'https://api.coinmarketcap.com/v1/ticker/';
$content = file_get_contents($url);
$json = json_decode($content, true);
print_r($json);
This will list all the values like this..
Array ( [0] => Array ( [id] => bitcoin [name] => Bitcoin [symbol] =>
BTC [rank] => 1 [price_usd] => 2448.04 [price_btc] => 1.0
[24h_volume_usd] => 1935820000.0 [market_cap_usd] => 40128026876.0
[available_supply] => 16391900.0 [total_supply] => 16391900.0
[percent_change_1h] => 3.47 [percent_change_24h] => -11.1
[percent_change_7d] => -12.29 [last_updated] => 1497512954 ) [1] =>
Array ( [id] => ...
How can I access certain values. For example if I want to display "name and symbol"?
The idea is to put name+symbol in select (dropdown) list, and when user changes selection, text field beside dropdown list automatically changes and shows properly market_cap_usd value.
I was able to go forward and parse some data..
foreach ($json as $key => $value) {
foreach ($value as $valuta => $vrednost) {
echo "<p>$valuta | $vrednost</p>";
}
}
I have in mind that this is not the best way.. Do I need to create object (how?) so I could call "name" value directly or something else...
EDIT:
I find a solution for my problem with accessing values. I was also able to put those values to select/dropdownmenu element.
Here is my version:
<form>
<label for="sel1">Select list (select one):</label>
<select class="selectpicker" data-live-search="true">
<?php
$url = 'https://api.coinmarketcap.com/v1/ticker/';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach ($json as $key => $value) {
echo "<option>" . $json[$key]['name'] ." (". $json[$key]['symbol'] .")</option>";
}
?>
</select>
</form>
Maybe will someone find some useful thing here for their own "problems".
What is missing for me right now is the connection between selection in dropdown and displaying correct value beside, based on that selection.

For your case, you'll need this code. I changed variable names to be more self-explaining.
$url = 'https://api.coinmarketcap.com/v1/ticker/';
$content = file_get_contents($url);
$decodedData = json_decode($content, true);
foreach ($decodedData as $currency) {
echo "<option value='" . $currency["id"] . "'>" . $currency["name"] ." (". $currency["symbol"] .")</option>";
}
What json_decode does is that it converts a JSON string into a multidimensional array in PHP. Then, you can iterate over it using foreach.

Hey use the code below.
<?PHP
$url = 'https://api.coinmarketcap.com/v1/ticker/';
$content = file_get_contents($url);
$json = json_decode($content, true);
echo $json[0]["bitcoin"];
?>

Related

Extract JSON ouput to get line by line key pair values using PHP

I would like to extract JSON ouput using PHP and tried below code but I'm getting output of single character instead of row wise values. I read similar posts but failed to get key pair values and getting output as single character. Wherever field values won't present, null is ok for that. How can I get output line by line for respective keys?
Tried code:
while (!feof($resultFile)) {
$line = fgets ($resultFile);
echo $line;
$someArray = json_decode($line);
foreach ($someArray as $key => $value) {
echo $value["key"] . ", " . $value["status"] . "<br>";
}
}
someArray output:
Array ( [key] => XYZ-6680 [status] => Open [components] => API [currentVersion] => Release1.2 [expectedVersion] => Array ( ) [customerInfo] => Default Calendar when the delegate responds to those invitations. ) Array ( [key] => XYZ-3325 [status] => Closed [components] => API [currentVersion] => Release 1.0 [expectedVersion] => Array ( [0] => Array ( [self] => https://bug.restify.com/rest/api/2/version/27771 [id] => 27771 [name] => Release1.2 [archived] => [released] => ) ) [customerInfo] => Fixed a number of bugs related to DA: * CrossMailboxSearch: Group label was shown even when all setting items of the group were hidden on New Account dialog ([https://bug.goog.restify/show_bug.cgi?id=1542 Bug 1542]) * After performing a bulk migration, the Delegated Admin user encountered an `HTTP Error 403` when attempting to download the list of provisioned accounts ([https://bug.goog.restify/show_bug.cgi?id=1039 Bug 1039]) ) Array ( [key] => XYZ-223 [status] => Closed [components] => API [currentVersion] => Release 1.3 [expectedVersion] => Array ( [0] => Array ( [self] => https://bug.restify.com/rest/api/2/version/29171 [id] => 29171 [name] => Release1.2 [archived] => [released] => ) ) [customerInfo] => "Default Calendar" user preference, `zimbraPrefDefaultCalendarId`. )
line output:
{"key":"XYZ-6680","status":"Open","components":"API","currentVersion":"Release1.2","expectedVersion":[],"customerInfo":"Default Calendar when the delegate responds to those invitations."} X, X
O, O
A, A
R, R
,
D, D
{"key":"XYZ-3325","status":"Closed","components":"API","currentVersion":"Release 1.0","expectedVersion":[{"self":"https://bug.restify.com/rest/api/2/version/27771","id":"27771","name":"Release1.2","archived":false,"released":false}],"customerInfo":"Fixed a number of bugs related to DA: * CrossMailboxSearch: Group label was shown even when all setting items of the group were hidden on New Account dialog ([https://bug.goog.restify/show_bug.cgi?id=1542 Bug 1542]) * After performing a bulk migration, the Delegated Admin user encountered an `HTTP Error 403` when attempting to download the list of provisioned accounts ([https://bug.goog.restify/show_bug.cgi?id=1039 Bug 1039])"} X, X
C, C
A, A
R, R
,
F, F
{"key":"XYZ-223","status":"Closed","components":"API","currentVersion":"Release 1.3","expectedVersion":[{"self":"https://bug.restify.com/rest/api/2/version/29171","id":"29171","name":"Release1.2","archived":false,"released":false}],"customerInfo":"\"Default Calendar\" user preference, `zimbraPrefDefaultCalendarId`."}X, X
C, C
A, A
R, R
,
", "
JSON (resultFile content):
{"key":"XYZ-6680","status":"Open","components":"API","currentVersion":"Release1.2","expectedVersion":[],"customerInfo":"Default Calendar when the delegate responds to those invitations."}
{"key":"XYZ-3325","status":"Closed","components":"API","currentVersion":"Release 1.0","expectedVersion":[{"self":"https://bug.restify.com/rest/api/2/version/27771","id":"27771","name":"Release1.2","archived":false,"released":false}],"customerInfo":"Fixed a number of bugs related to DA: * CrossMailboxSearch: Group label was shown even when all setting items of the group were hidden on New Account dialog ([https://bug.goog.restify/show_bug.cgi?id=1542 Bug 1542]) * After performing a bulk migration, the Delegated Admin user encountered an `HTTP Error 403` when attempting to download the list of provisioned accounts ([https://bug.goog.restify/show_bug.cgi?id=1039 Bug 1039])"}
{"key":"XYZ-223","status":"Closed","components":"API","currentVersion":"Release 1.3","expectedVersion":[{"self":"https://bug.restify.com/rest/api/2/version/29171","id":"29171","name":"Release1.2","archived":false,"released":false}],"customerInfo":"\"Default Calendar\" user preference, `zimbraPrefDefaultCalendarId`."}
Expected output:
Line by line values of key, status, components, currentVersion, expectedVersion, customerInfo.
Actual output:
First of all, #Curious_mind is right about forcing output of json_decode as an associative array with second parameter to true. Then I think you should get what you want by echoing directly $key and $value, like so:
while (!feof($resultFile)) {
$line = fgets ($resultFile);
echo $line;
$someArray = json_decode($line,true);
foreach ($someArray as $key => $value) {
echo key . ", " . $value . "<br/>";
}
}
BUT, careful, if $value is an array, you will get an error (can't just echo an array), so you need to handle the array resulting of you json recusivly.
I adapt the function found here: Echo a multidimensional array in PHP
and added some testing to display string for boolean value too.
It should display the json values as you wish:
while (!feof($resultFile)) {
$line = fgets ($resultFile);
//echo $line;
$someArray = json_decode($line,true);
RecursiveWrite($someArray);
}
function RecursiveWrite($array) {
foreach ($array as $key => $value) {
echo $key .', ';
if(is_array($value)) {
echo "<br>";
RecursiveWrite($value);
}
elseif(is_bool($value)) {
echo ($value? 'true' : 'false') . "<br>";
}
else {
echo $value . "<br>";
}
}
}
How about that $someArray = json_decode($line,true);? because without the 2nd parameter true, json_decode() will return results as object and for that case you've to use $value->key while accessing keys not $value['key']
while (!feof($resultFile)) {
$line = fgets ($resultFile);
echo $line;
$someArray = json_decode($line,true); # see the tweak here
foreach ($someArray as $key => $value) {
echo $value["key"] . ", " . $value["status"] . "<br/>";
}
}
First I agree with Dexter0015's answer. It should be marked as the correct answer as it will deal with a wide variety of results.
I just thought I'd throw my two cents in for a shorter and very problem specific to the user's issue.
/* Load up a record that is json encoded */
$json = '{"key":"XYZ-6680","status":"Open","components":"API","currentVersion":"Release1.2","expectedVersion":[],"customerInfo":"Default Calendar when the delegate responds to those invitations."}';
/* Use json_decode to convert the JSON string to a PHP Array. Be sure and set the second parameter to true in json_decode to get an array and not an object */
$array = json_decode($json, true);
/*
* Now iterate through the result extracting the key and value of the array created from json decode
* There could be instances (expectedVersion) that may have an array of values. So test to see
* if the array value is an array. If so using print_r, otherwise just echo out the $value as a string
*/
foreach ($array as $key => $value) {
if (!is_array($value)) {
echo '* Key ' . $key . ' has a value of :' . $value . PHP_EOL;
} else {
echo "* Key " . $key . ' has an array of values :' . print_r($value, true) . PHP_EOL;
}
}

PHP - get value from JSON

Before i decode my JSON i get this result:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1},
"2":[{"membership_id":3,"group_id":1,"user_id":2}
}
How would i specify that i want to select the one who has 'user_id' == 2 and return membership_id value?
My attempt, but i get undefined value 'user_id':
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value['user_id'] == $cid){
$mid = $value['membership_id'];
}
}
echo $mid;
Basically i guess i would first have to select the right object and go through it with the foreach, but here i got a bit lost in the situation.
Use Array-Functions:
$json = '{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}';
$array = json_decode($json, true);
$searchUserID = 2;
$filteredArray = array_filter($array, function($elem) use ($searchUserID){
return $searchUserID == $elem[0]['user_id'];
});
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
echo "Membership-ID: ".$mid;
array_filter uses a callback function that iterates over every element of the array. If the callback function returns true, that element is assigned to $filteredArray. No need for a foreach loop that way.
But the return value is the whole array element:
Array
(
[2] => Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
)
So you have to extract your membership_id.
Read the following line from inside out.
First, we fetch the first entry of the array with array_shift (since we have only one entry, this will be our desired entry).
Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
We pass this array on to array_column to find the entry in the encapsulated array with the column name membership_id. Since array_column again returns an array,
Array
(
[0] => 3
)
we get the (one and only) entry by adding [0] to the end of this command.
Since the last part is a little complicated, here's a torn apart version of it:
$firstEntryOfFilteredArray = array_shift($filteredArray);
$arrayWithValueOfColumnMembershipID = array_column($firstEntryOfFilteredArray, 'membership_id');
$membership_id = $arryWithValueOfColumnMembershipID[0];
These three lines are concatenated into this:
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
here's a working example: http://sandbox.onlinephpfunctions.com/code/8fe6ede71ca1e09dc68b2f3bec51743b27bf5303
I'm assuming the JSON actually looks like:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}
Each element of the object is an array for some reason. So you need to index it with $value[0] to access the object contained inside it.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value[0]['user_id'] == $cid){
$mid = $value[0]['membership_id'];
break;
}
}
echo $mid;
If the arrays can contain multiple elements, you'll need nested loops.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
foreach ($value as $object) {
if($object['user_id'] == $cid){
$mid = $object['membership_id'];
break 2;
}
}
}
echo $mid;
This is a bit speculative, but I think the data is indexed by user ID. If that's the case, it makes the lookup much simpler.
After decoding with $myjson = json_decode($s_o, true);
Just find the record by ID and get the membership_id from the matching row.
$membership_id = reset($myjson['2'])['membership_id'];`
You should probably verify that that ID exists, so maybe something like:
$membership_id = isset($myjson['2']) ? reset($myjson['2'])['membership_id'] : null;
If I'm wrong and the fact that the row numbers match the user_id is just a coincidence, then never mind :)

Add white space after each xml element usinh php

I have created a xml from an array using php.The result is listed below.
<Mst><Mstrow><sCode>10</sCode>Test<sName></sName></Mstrow></Mst>
But I want to show this xml with white spaces between each element lik this
<Mst> <Mstrow> <sCode>10</sCode> <sName>Test</sName> </Mstrow> </Mst>
Below is my code ,
$results = Array ( [0] => Array ( [sCode] => 10 [sName] => Test) ) ;
$main = $dom->appendChild($dom->createElement('Mst'));
if($results != Array()){
foreach ($results as $datas) {
$row ->$main->appendChild($dom->createElement('Mstrow'));
foreach ($datas as $name => $value) {
$row
->appendChild($dom->createElement($name))
->appendChild($dom->createTextNode($value));
}
}
}
Please provide a solution
I may have missunderstood the qn, and I assume in your (pre) example test should be between <sName> tags. I would have thought a simple string replace before you echo/save your XML string would do the trick?
e.g.
echo str_replace( '><' , '> <', $myXml->asXML());

Iterate over JSON file using PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a JSON file containing a list of universities around the world. I want to get only specific universities where a field in the array matches what I need to select. The problem I face is that each university has it's own ID number which makes me unable to figure out how to iterate over the Array. The JSON file can be found on this GitHub repo.
The code that makes me convert the JSON file to an array:
<?php
$json = file_get_contents('universities_list.json');
$universityArray = json_decode($json, true);
print_r($universityArray);
?>
And a sample of what I get is:
[2942] => Array
(
[alpha_two_code] => EG
[country] => Egypt
[domain] => aast.edu
[name] => Arab Academy for Science & Technology
[web_page] => http://www.aast.edu/
)
[2943] => Array
(
[alpha_two_code] => EG
[country] => Egypt
[domain] => akhbaracademy.edu.eg
[name] => Akhbar El Yom Academy
[web_page] => http://www.akhbaracademy.edu.eg/
)
What is the best or appropriate way to print out only the universities with alpha_two_code == 'EG' or == 'Egypt' for example?
I read the documentation on foreach loop and the examples as well. But still can't get the logic to get what I mentioned above.
Check this return only a specific country
<?php
$json = file_get_contents('university.json');
$universityArray = json_decode($json, true);
universities= array()
for($i=0; $i< count($universityArray); $i++)
{
if($universityArray[$i]["country"] == "Morocco")
universitises[] = $universityArray[$i];
}
var_dump($universitises);
?>
You can use alpha_two_code as index.
$indexed = [];
foreach($universityArray as $university){
$index = $university['alpha_two_code'];
if(!isset($indexed[$index])){
$indexed[$index] = [];
}
$indexed[$index][] = $university;
}
Now you will have universities seperated by alpha_two_code which you can directly access.
print_r($indexed['EG']);
Now as per the best and appropriate part, you may want to cache $indexed. You can create a directory for universities and save JSON encoded $indexed there.
You need to read the manual.
Try this:
$names = array();
foreach($universityArray as $u) {
if($u['alpha_two_code'] == 'EG' || $u['country'] == 'Egypt'){
$names[] = $u['name'];
}
}
print_r($names);
you can use the array_filter http://php.net/manual/en/function.array-filter.php function here with a callback. You can then use array_column http://php.net/manual/en/function.array-column.phpto grab just the 'name' column.
$json = file_get_contents('https://github.com/Hipo/university-domains-list/blob/master/world_universities_and_domains.json');
$universityArray = json_decode($json, true);
$filterBy = 'EG';
$newArray = array_filter($universityArray, function ($var) use ($filterBy) {
return ($var['alpha_two_code'] == $filterBy);
});
print_r($newArray);
$names = array_column($newArray, 'name');
print_r($names);

php get the text into an array list

I have an array in the database. When I used print_r($variable_name), I got the array like this
Array
(
[0] => Array
(
[attribute_name] => Disk space,Color,Processor
)
)
So to get the value of attribute_name I tried this
foreach($attributes_name as $key=>$val) {
echo $val['attribute_name'];
}
Here I got the result like Disk space,Color,Processor. But I want the result should come like a list
<li>Disk Space</li>
<li>Color</li>
<li>Processor</li>
So can someone tell me how to do this?
Try this :
<?php
$arr = array(array("attribute_name" => "Disk space,Color,Processor"));
foreach($arr as $val) {
$resultArr = explode(",",$val['attribute_name']);
foreach($resultArr as $value){
echo "<li>".$value."</li>";
// Add id in li
echo "<li id='".str_replace(" ","_", strtolower($value))."'>".$value."</li>";
}
}
?>

Categories