json and PHP parse - php

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>";
}
}

Related

Loop JSON String response in PHP Foreach

I'm trying to print values of a JSON response in PHP. Inside the contents are:
data
local
acao
detalhes
Codes:
<?php
header('Content-type: text/html; charset=UTF-8');
$url = "http://developers.agenciaideias.com.br/correios/rastreamento/json/RJ290474594CN";
$c_url = file_get_contents($url);
$c_url = utf8_encode($c_url);
$results = json_decode($c_url);
echo $c_url;
?>
I've tried using foreach but wasn't successful in implementing them in said JSON response.
Here is a JSON String Example:
[{"data":"07\/12\/2014 11:19","local":"CHINA - CHINA\/CN","acao":"postado","detalhes":"-"},{"data":"09\/12\/2014 12:03","local":"CHINA - CHINA\/CN","acao":"encaminhado","detalhes":"Em tr\u00e2nsito para Unidade de Tratamento Internacional - BRASIL\/BR"},{"data":"29\/12\/2014 12:34","local":"UNIDADE TRAT INTERNACIONAL PARANA - Curitiba\/PR","acao":"conferido","detalhes":"Recebido\/Brasil "}]
If you just want to print values just print them accordingly using foreach. After getting the response, use json_decode(). That ut8f_encode() is superfluous.
$url = "http://developers.agenciaideias.com.br/correios/rastreamento/json/RJ290474594CN";
$data = json_decode(file_get_contents($url), true);
foreach($data as $values) {
echo $values['data'] . '<br/>';
echo $values['local'] . '<br/>';
echo $values['acao'] . '<br/>';
echo $values['detalhes'] . '<br/>';
}
Sample Output
Or:
$url = "http://developers.agenciaideias.com.br/correios/rastreamento/json/RJ290474594CN";
$data = json_decode(file_get_contents($url), true);
foreach($data as $values) {
foreach($values as $key => $value) {
echo "{$key}: $value <br/>";
}
echo '<hr/>';
}

How to parse json in php from url

Im new to json, so i gotta ask you a maybe really simple questions.
I've tried searching around but have not found anything I can get to work.
I have called an API and received the data in json.
And now comes my problem parsing it through my php, it "will not find anything."
My code looks like this:
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept: application/vnd.travify.v1+json\r\n"
)
);
$context = stream_context_create($opts);
$url = 'http://oda.ft.dk/api/Sag?$select=titel,Sagskategori/kategori&$expand=Sagskategori';
$output = file_get_contents($url, false, $context);
$string = file_get_contents($url, false, $context);
$result = json_decode($string, true);
$i = -1;
foreach ($result as $data) {
$i++;
echo "#";
echo $i;
echo "<br>";
echo "<b>Test 1:</b>";
echo "<br>";
if(!empty($result[$i]['value']['Sagskategori']['kategori'])){
echo $result[$i]['value']['Sagskategori']['kategori'];
}else{
echo "Intet fundet.";
}
echo "<hr>";
}
The json code can be find here: http://oda.ft.dk/api/Sag?$select=titel,Sagskategori/kategori&$expand=Sagskategori
Can anyone of you see my fail in the code, and get me on the right way :-) ?
Please replace
foreach ($result as $data) {
by
foreach ($result["value"] as $data) {
And now you can iterate to your value array and get all informations from $data
You don't need use $i, $data contains correct $result[$i] value
foreach ($result["value"] as $data) {
echo "#";
echo "<br>";
echo "<b>Test 1:</b>";
echo "<br>";
if(!empty($data['Sagskategori']['kategori'])){
echo $data['Sagskategori']['kategori'];
}else{
echo "Intet fundet.";
}
echo "<hr>";
}
The JSON starts like this:
{
"odata.metadata":"...snip...","value":[
{
So the array is inside the value object.
The correct code should be:
foreach ($result['value'] as $data) {
// snip
if(!empty($result['value'][$i]['Sagskategori']['kategori'])){
echo $result['value'][$i]['Sagskategori']['kategori'];
}
Also, inside the loop, $result['value'][$i]['Sagskategori']['kategori']; is strictly the same as using $data['Sagskategori']['kategori'];.

How to print jSON values with loop

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&currencyCode=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/>';
}
}

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 json, finding info and linking it with 4chan api

If I wanted to echo the link of a general thread on 4chan.
Here's what I was thinking of, however I have no idea on what to do
$jsonurl = "http://a.4cdn.org/vg/catalog.json";
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);
foreach( $json_output as $no )
{
if(strpos(sub, 'DOTA')) { //Not sure how I would do this
//echo the "no" of it in the json
}
}
Had to look at the JSON data to see what you were looking for. Give this a try
$jsonurl = "http://a.4cdn.org/g/catalog.json";
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);
foreach ($json_output as $page) {
foreach($page->threads as $thread) {
if (isset($thread->sub)) {
$sub = $thread->sub;
$no = $thread->no;
echo $sub . ', Thread Number: ' . $no . '<br />';
/*
if (strpos($sub, 'DOTA') !== false) {
echo 'Found DOTA!!! Thread Number is: ' . $thread->no;
}
*/
}
}
}
You should study the JSON data that you receive in order to know how to extract the data. This is one way of doing it:
foreach( $json_output as $page ) {
foreach ($page->threads as $t) {
echo 'http://boards.4chan.org/vg/res/' . $t->no . ', ';
}
}

Categories