I am new to PHP, I have some data from API in json format.
In php i tried
$response = \Httpful\Request::get($uri)->send();
$json = json_decode($response, true);
foreach($json as $k=>$val):
echo '<b>Name: '.$k.'</b></br>';
endforeach;
echo $response;
echo "<br />";
print_r($json);
echo "<br />";
echo ($json["genres"][0]);
But I am unable to read the array content. Can someone please help me how to parse this PHP array in a loop. Is there any php library to simplify this?
You can try to use the foreach loop in PHP as follows, which worked for me.
foreach(json_data as $key => $val){
echo $key . ":" . $val;
}
I hope it helps.
firstly you wrongly used php's foreach, second you have to use $json['genres'] to access the inner array
foreach($json['genres'] as $k=>$val)
{
echo $k.':'.$val['id'].'_'.$val['name'];
}
Related
Hi I'm trying get a json from fixer.io and then for each rates echo it but cant get it to work.
the code are
<?php
function usd(){
echo 'HEJ test';
$fixer_access_key = my_access_key;
$url= 'https://data.fixer.io/api/latest?access_key=' . $fixer_access_key;
echo $url;
$json = file_get_contents($url);
$data = json_decode($json);
echo $url . "<br>";
echo 'printing json foreach <br>';
foreach($data as $obj){
echo '...';
$prefix = $obj;
echo $prefix;
echo '<br>';}
echo 'done printing json foreach';
}
usd(); ?>
and the result are:
https://data.fixer.io/api/latest?access_key=my_fixer_key
printing json foreach
done printing json foreach
instead of
$data = json_decode($json);
use
$data = json_decode($json, true);
This should allow foreacha to works - however you will only see first level of json object keys (not nested ones). The second parameter of json_decode change result from object to array.
You will also need to change foreach - to following: foreach($data as $key => $obj) and inside it echo $obj to echo $key;.
Here is simplified working example.
ALTERNATIVE SOLUTION
If working foreach is not your goal but rather pretty printed json, then instead use following code:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
echo $json_string;
I am using the following code to print the output of the jSON response but when I try to print
echo $obj->HotelListResponse->customerSessionId; // This is working.
echo $obj->HotelListResponse->HotelList->HotelSummary->name; // This is not working.
When the response contains only one node then its printing perfectly but when there are multiple nodes with same name then its not printing. I tried using foreach just like the below. I also tried using while loop but still I am unable to print the list of hotel names.
My jSON decoded output is like http://pastebin.com/Fr21DkEk
Total code:
$url = "https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55505&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_AU¤cyCode=AUD&xml=<HotelListRequest><city>Brisbane</city><stateProvinceCode>QLD</stateProvinceCode><countryCode>AU</countryCode><arrivalDate>10/16/2014</arrivalDate><departureDate>10/18/2014</departureDate><RoomGroup><Room><numberOfAdults>2</numberOfAdults></Room></RoomGroup><numberOfResults>25</numberOfResults></HotelListRequest>";
$json = file_get_contents($url);
$obj = json_decode($json);
foreach($obj as $val) {
echo $val->HotelListResponse->HotelList->HotelSummary->name;
}
Try this
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
echo $val->name . '<br/>';
}
HotelSummary is an array:
echo $val->HotelListResponse->HotelList->HotelSummary[0]->name;
If you want all of the hotel summaries:
foreach($obj as $val) {
foreach($val->HotelListResponse->HotelList->HotelSummary as $sum) {
echo $sum->name;
}
}
Yes you can directly access them inside the foreach. Like this:
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
// ^^
// since you're interested on just names, you can point it directly on that object, then each of that batch is in `$val`
echo $val->name . '<br/>';
}
// or start from the parent
foreach($obj as $values) {
$customerSessionId = $values->customerSessionId;
echo $customerSessionId . '<hr/>';
$hotelList = $values->HotelList;
foreach($hotelList->HotelSummary as $hotelsummary) {
echo $hotelsummary->name . '<br/>';
}
}
hi im trying to get data from json file using php with a url query eg http://192.168.1.104/testing_JSON/zjson2.php?name=nas
The following is my code i dont know the syntax to use for retrieving the query.
Thanks in advance
$name = ( $_GET['$name'] );
$json_string = file_get_contents("http://192.168.1.104/testing_JSON/newjson.json");
$parsed_json = json_decode($json_string, true);
$parsed_json = $parsed_json['contacts'];
//pr($parsed_json);
foreach($parsed_json as $key => $value)
{
echo $value['$name'] . '<br>';
echo $value['name'] . '<br>';
// etc
}
?>
Why i can't get out the values from the json file with PHP?
I get zero values? Have tried for hours.
<?php
$json_string = 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=44';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
print_r($data);
echo "<br><br><br><br>";
foreach ($data as $recenttrades) {
echo "VALUES('{$recenttrades->quantity}', '{$recenttrades->price}' ";
}
?>
Update: but can't get the value from primaryname and primarycode.
I have tried this:
$json_string = 'http://pubapi.cryptsy.com/api.php?method=marketdatav2';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
//print_r($data);
foreach ($data["market"] as $markets) {
echo "Primary code: <strong>{$markets['primarycode']}</strong><br>";
foreach($markets as $market) {
foreach($market as $attributes) {
foreach($attributes["recenttrades"] as $recenttrade) {
echo "quantity: " . $recenttrade['quantity'] .", price: " . $recenttrade['price'] . "<br>";
}
}
}
}
Others have mentioned that you're dealing with nested arrays, not objects. Along with pointing out the issue of being nested rather deeply, I would suggest digging down with foreach (I will probably be crucified for this):
<?php
$json_string = 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=44';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
//print_r($data);
echo "<br><br><br><br>";
foreach ($data as $markets) {
foreach($markets as $market) {
foreach($market as $attributes) {
foreach($attributes["recenttrades"] as $recenttrade) {
//echo "<pre>";
//print_r($recenttrade);
//echo "</pre>";
echo "VALUES('{quantity: " . $recenttrade['quantity'] ."}', 'price: {" . $recenttrade['price'] . "}')";
}
}
}
}
?>
This will ensure that you grab every recentrades item at this level of the array. This way you are prepared for other markets to be added to the API and your code isn't locked into searching only in the item named "FST".
recenttrades is nested pretty deeply in that array. Try
foreach ($data['return']['markets']['FST']['recenttrades'] as $recenttrades) {
recenttrades is several levels nested, so simply doing foreach($data as $recenttrades) is not sufficient.
You need to do:
$recentTrades = $data['return']['markets']['FST']['recenttrades'];
foreach($recentTrades as $recentTrade) {
...
}
recenttrades is nested deeply and you're asking for arrays, not objects. This seems to work:
foreach ($data['return']['markets']['FST']['recenttrades'] as $recenttrades) {
echo "VALUES('{$recenttrades['quantity']}', '{$recenttrades['price']}' ";
}
In response to your update, where you want to loop over markets, try this:
foreach ($data['return']['markets'] as $market) {
echo "Primary code: <strong>{$market['primarycode']}</strong><br>";
foreach ($market["recenttrades"] as $recenttrade) {
echo "quantity: " . $recenttrade['quantity'] .", price: " . $recenttrade['price'] . "<br>";
}
}
Could someone assist me in helping me display more than 1/2 results?
Here is my code:
$url = "http://otter.topsy.com/search.json?q=debt%20management&window=a&perpage=10";
$jsonfile = file_get_contents($url);
$obj = json_decode($jsonfile);
foreach($obj as $result) {
echo $obj->response->list[0]->trackback_permalink;
echo "<br />";
echo $obj->response->list[0]->trackback_author_nick;
echo "<br />";
echo $obj->response->list[0]->content;
echo "<br /><br />";
}
?>
*Note: I have taken out my API key.
Using that code it shows two of the same results.
Anyone got a solution?
You iterate over $obj which is the top-level object containing two elements (request and response). Since you probably want to iterate over the response list, this is what you need:
foreach($obj->response->list as $result) {
echo $result->trackback_permalink;
echo "<br />";
echo $result->trackback_author_nick;
echo "<br />";
echo $result->content;
echo "<br /><br />";
}
Ah, just saw it:
remove the $obj++ ! You increment twice during each loop run. Once by the foreach() loop iterating itself, and once by manually iterating.