PHP Best Way to Create Variable from API Content - php

I am very beginner in programmer and I am learning.
I am sorry if my question is too bad.
I want to create variable in php from api content, for example:
This contents is from this URL: http://example.com/api
{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}
<?php
$content = file_get_contents("http://example.com/api");
$content = str_replace('"', "", $content);
$content = str_replace(":", "=", $content);
$content = str_replace(",", "&", $content);
parse_str($content);
echo $name; //John
echo $age; //20
echo $genre; //male
echo $language //[{id <======== here is my problem
?>
My problem is when I am getting an array like "language", how to fix it?
Thanks for help.

U can use the http://www.php.net/json_decode in two ways :
This is object oriented :
$str = '{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}';
$json = json_decode($str);
echo 'name: ' . $json->{'name'} .'<br>';
echo 'age: ' . $json->{'age'} .'<br>';
echo 'genre: ' . $json->{'genre'} . '<br>';
foreach($json->{'language'} as $data){
echo 'id: ' . $data->{'id'} . '<br>';
echo 'name: ' . $data->{'name'} . '<br>';
}
As an associative array :
$json = json_decode($str, true);
echo 'name: ' . $json['name'] .'<br>';
echo 'age: ' . $json['age'] .'<br>';
echo 'genre: ' . $json['genre'] . '<br>';
foreach($json['language'] as $data){
echo 'id: ' . $data['id'] . '<br>';
echo 'name: ' . $data['name'] . '<br>';
}

json_decode() will help you to convert the string data to something more accessible:
<?php
// Instead of your fetched data we use static example data in this script
//$content = file_get_contents("http://example.com/api");
$content = '{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}';
// Convert json data to object
$data = json_decode($content);
// access object properties by using "->" operator
echo $data->name;
echo $data->age;
echo $data->genre;
// language is an array of objects, so let's look at each language object...
foreach($data->language as $lang) {
// ... and extract data using "->" again
echo $lang->id;
echo $lang->name;
}
A live example of this code can be found at http://sandbox.onlinephpfunctions.com/code/6df679c3faa8fff43308a34fb80b2eeb0ccfe47c

As pointed out by #fusionK, the response from the api request is a json string so convert to an object ( or array if preferred ) using json_decode ( json_decode( $data,true ) for an array )
Once it is decoded it is straightforward to access the properties of the object.
<?php
/* capture and decode response from api - creates an object */
$content = json_decode( file_get_contents("http://example.com/api") );
/* using object notation to access properties */
echo $content->name.' '.$content->age.' '.$content->genre;
/* for the language which is an array of objects */
$lang=$content->language;
foreach( $lang as $language ){
$obj=(object)$language;
echo $obj->id.' '.$obj->name;
}
?>

Related

How do I get one json value value each?

in this my php code
echo $_POST[result];
in this my php result
{
"result_code":0,
"err_cd":"",
"result_msg":"",
"store_id":"M20C2685",
"status":"APPROVED",
"order_no":"600a2a044c9be",
"tr_no":725,
"tr_price":1000,
"pay_price":1000,
"approved_day":"20210122",
"approved_time":"102744",
"param1":"",
"param2":""
}
I want to print out each value one by one. What should I do?
json_decode Parsing JSON
<?php
$str = '{"result_code":0,
"err_cd":"",
"result_msg":"",
"store_id":"M20C2685",
"status":"APPROVED",
"order_no":"600a2a044c9be",
"tr_no":725,
"tr_price":1000,
"pay_price":1000,
"approved_day":"20210122",
"approved_time":"102744",
"param1":"",
"param2":""
}';
$arr = json_decode($str, true);
echo $arr['err_cd'] . PHP_EOL;
echo $arr['result_msg'] . PHP_EOL;
echo $arr['store_id'] . PHP_EOL;
echo $arr['status'] . PHP_EOL;
// ......
// Circulates each value in the array
foreach ($arr as $item) {
echo $item . PHP_EOL;
}

how to get value of id and name from json response

I want to get value of id and name from the string given below in php. Can any body help me please.
string(35400) "{"cities":[{"id":"3279","name":"Narasaraopet"},{"id":"1852","name":"Srirangapatna"}
That's not really a valid json (missing ]} at the end), but assuming you removed something from it just to post the question, do it like this:
$json = '{"cities":[{"id":"3279","name":"Narasaraopet"},{"id":"1852","name":"Srirangapatna"}]}';
$decoded = json_decode($json, true);
foreach($decoded['cities'] as $v){
echo 'ID: ' . $v['id'] . '<br>';
echo 'Name: ' . $v['name'];
echo '<br><br>';
}
Output:
ID: 3279
Name: Narasaraopet
ID: 1852
Name: Srirangapatna
To use it as objects, you can ommit the second argument, like so:
$decoded = json_decode($json);
Then you'd access the values object-like:
foreach($decoded->cities as $v){
echo 'ID: ' . $v->id . '<br>';
// ...
Read more about json_decode.
Use the function json_decode(), then you'll have an array.

PHP foreach - parsed json from URL

I have a JSON file called from an URL. I've checked and I'm getting the the data from the URL.
I've tried a lot, but I can't get the loop foreach to work - what is wrong?
<?php
$url = 'http://banen.klintmx.dk/json/ba-simple-proxy.php?url=api.autoit.dk/car/GetCarsExtended/59efc61e-ceb2-463b-af39-80348d771999';
$json= file_get_contents($url);
$data = json_decode($json);
$rows = $data->{'contents'};
foreach($rows as $row) {
echo '<p>';
$FabrikatNavn = $row->{'contents'}->{'FabrikatNavn'};
$ModelNavn = $row->{'contents'}->{'ModelNavn'};
$PrisDetailDkk = $row->{'contents'}->{'PrisDetailDkk'};
echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
echo '</p>';
}
?>
The actual problem is you trying to access content object again. Just change your foreach snippet with,
foreach ($rows as $row) {
echo '<p>';
$FabrikatNavn = $row->FabrikatNavn;
$ModelNavn = $row->ModelNavn;
$PrisDetailDkk = $row->PrisDetailDkk;
echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
echo '</p>';
}
DEMO.
Use json_decode($data, true) so that it parses the JSON content into a PHP array. So it will be something like
$rows = $data['contents'];
foreach($rows as $row) {
echo '<p>';
$FabrikatNavn = $row['contents']['FabrikatNavn'];
$ModelNavn = $row['contents']['ModelNavn'];
$PrisDetailDkk = $row['contents']['PrisDetailDkk'];
echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
echo '</p>';
}
Take a look at using json_decode($json, true) as this will convert the data to an associative array which seems to be the way you are approaching the solution.
Check the output by printing with var_dump() or print_r()
Try like this
$data = json_decode($json,true); //decode json result as array and thenloop it
print '<pre>';
print_r($data);
foreach($data as $row){
//do something here
}

PHP (XML TO ARRAY) Getting the attribute of the xml that is array

Hello I am getting games in the spilgames xml. I managed to convert it to array but 1 problem came up again the problem is that the string I want to get is inside of an array or an attribute of 1 node xml .I can't get the attribute.
I want to get the attribute.
website of spilgames: here
Code I have so far:
<?php
$xml = simplexml_load_string(file_get_contents('http://publishers.spilgames.com/rss-3?limit=100&format=xml&category=Action')); /* Get the xml */
$json = json_encode($xml);
$games = json_decode($json); /* Make it an array */
$game = $games->entries->entry;
foreach($game as $entry) { /* Each game information */
echo $entry->title;
echo $entry->id;
echo $entry->description;
echo $entry->category;
echo $entry->subcategory;
echo $entry->technology;
echo $entry->player->url;;
echo $entry->thumbnails->small->url; /* Problems starts here */
/* Because the thumbnails has 3 child but the info is inside of each child */
}
?>
I am getting the xml not json in spilgames because I don't know how json works.
If I were you I would learn how JSON works because it will make your life easier:
<?php
$json = file_get_contents('http://publishers.spilgames.com/rss-3?limit=100&format=json&category=Action');
$data = json_decode($json);
foreach ($data->entries as $entry) {
echo $entry->title . "\n";
echo $entry->id . "\n";
echo $entry->description . "\n";
echo $entry->category . "\n";
echo $entry->subcategory . "\n";
echo $entry->technology . "\n";
echo $entry->thumbnails->small . "\n";
echo $entry->thumbnails->medium . "\n";
echo $entry->thumbnails->large . "\n";
}
?>

How to read json properties using PHP

How to get all pid and styles attribute from following json data with minimum loop in php
{"general":{"note":{"display":false}},"elements":{"the-1":{"index":1,"src":"shirt1.png","pid":"pid-3563130","angle":0,"styles":"background:transparent;top:51.80000305175781px;left:122px;width:80px;height:80px;","background":"transparent","pos":{"top":51.80000305175781,"left":122},"size":{"width":80,"height":80},"details":{"other":""}},"the-2":{"index":2,"src":"shirt2.png","pid":"pid-132002","angle":0,"styles":"background:transparent;top:44.80000305175781px;left:155px;width:80px;height:80px;","background":"transparent","pos":{"top":44.80000305175781,"left":155},"size":{"width":80,"height":80},"details":{"other":""}}}}
Thanks
$str = '{"general":{"note":{"display":false}},"elements":{"the-1":{"index":1,"src":"shirt1.png","pid":"pid-3563130","angle":0,"styles":"background:transparent;top:51.80000305175781px;left:122px;width:80px;height:80px;","background":"transparent","pos":{"top":51.80000305175781,"left":122},"size":{"width":80,"height":80},"details":{"other":""}},"the-2":{"index":2,"src":"shirt2.png","pid":"pid-132002","angle":0,"styles":"background:transparent;top:44.80000305175781px;left:155px;width:80px;height:80px;","background":"transparent","pos":{"top":44.80000305175781,"left":155},"size":{"width":80,"height":80},"details":{"other":""}}}}';
$arr = json_decode($str, true);
foreach ($arr['elements'] as $element) {
echo 'pid: ' . $element['pid'] . '<br />';
echo 'styles: ' . $element['styles'] . '<br />';
}
use json_decode function in PHP to get assosiative array.
<?php
$myJson = '{"general":{"note":{"display":false}},"elements":{"the-1":{"index":1,"src":"shirt1.png","pid":"pid-3563130","angle":0,"styles":"background:transparent;top:51.80000305175781px;left:122px;width:80px;height:80px;","background":"transparent","pos":{"top":51.80000305175781,"left":122},"size":{"width":80,"height":80},"details":{"other":""}},"the-2":{"index":2,"src":"shirt2.png","pid":"pid-132002","angle":0,"styles":"background:transparent;top:44.80000305175781px;left:155px;width:80px;height:80px;","background":"transparent","pos":{"top":44.80000305175781,"left":155},"size":{"width":80,"height":80},"details":{"other":""}}}}';
$myArray = json_decode($myJson,true);
$myInnerArray = $myArray['elements'];
$styles = array();
foreach($myInnerArray as $element)
$styles[] = $element['styles'];
print_r($styles);
?>
PHP has great abilities to handle json.
Let's assume the JSON string you've posted above is stored in a PHP variable $myJSON.
So we can easily store an associative array of these values into $myJSONArray like so:
$myJSONArray = json_decode( $myJSON, true );
So, now we just loop through:
foreach( $myJSONArray['elements'] as $arr => $key )
echo( "A PID: " . $key['pid'] . "\n" );
See it in action on Codepad.
$json = json_decode('{"general":{"note":{"display":false}},"elements":{"the-1":{"index":1,"src":"shirt1.png","pid":"pid-3563130","angle":0,"styles":"background:transparent;top:51.80000305175781px;left:122px;width:80px;height:80px;","background":"transparent","pos":{"top":51.80000305175781,"left":122},"size":{"width":80,"height":80},"details":{"other":""}},"the-2":{"index":2,"src":"shirt2.png","pid":"pid-132002","angle":0,"styles":"background:transparent;top:44.80000305175781px;left:155px;width:80px;height:80px;","background":"transparent","pos":{"top":44.80000305175781,"left":155},"size":{"width":80,"height":80},"details":{"other":""}}}}', true);
$elements = $json['elements'];
foreach($elements as $element){
$pid = $element['pid'];
$styles = $element['styles'];
echo $pid.': '.$styles.'<br />';
}
Example here

Categories