Print JSON string in dropdown menu - php

I am getting a problem in generating values of a JSON string into a dropdown menu.I have a JSON API
http://service.proventustechnologies.com/api/json?username=demo&token=4ce26206-025d-11dc-8314-0800200c9a66&method=getattributevalues&dimensionId=10
When you click it you will see many values like this.
{
"response": {
"id": 10,
"values": [
{
"id": 258,
"value": "Cameras"
},
{
"id": 2581,
"value": "GPS Navigation"
},
{
"id": 259,
"value": "MP3 Players"
},
{
"id": 260,
"value": "Cell Phone/PDA"
},
{
"id": 6377,
"value": "Digital Photo Frame"
},
{
"id": 110,
"value": "Motherboard"
},
{
"id": 108,
"value": "Desktop/Server"
},
{
"id": 109,
"value": "Notebook"
},
{
"id": 10738,
"value": "E-Book Reader"
}
],
"name": "System Type"
},
"status": "ok"
}
I want to print all the values such as Cameras,GPS Navigation in a dropdown menu.Thank you for any kind of help.

Use json_decode to convert json encoded string into PHP variable:
<?php
$json = file_get_contents($your_url);
$obj = json_decode($json);
echo $obj->response->id; // prints 10 (based on your sample code)
?>

I can't really get a feel for what your level of knowledge is, but you should load your data in a html select element for example like this:
<?php
echo '<select>';
$jsonData = file_get_contents($url);
$jsonDataObject = json_decode($jsonData);
foreach($jsonDataObject->response->values as $option){
echo '<option value=' . $option->id . '>' . $option->value . '</option>';
}
echo '</select>';
?>

hridaynehu,
Its very easy to populate the select box using your json array values. Follow below line of code.
<?php
$url = 'http://service.proventustechnologies.com/api/json?username=demo&token=4ce26206-025d-11dc-8314-0800200c9a66&method=getattributevalues&dimensionId=10';
$content = file_get_contents($url);
$jsonArray = json_decode($content, true);?>
<select name="json_populate"><?php
foreach($jsonArray->response->values as $jsonValue) { ?>
<option value="<?php echo $jsonValue->id; ?>"><?php echo $jsonValue->value; ?></option>
<?php } ?>
</select>
Please mark it answer if it helps you. Because it may help others too.
With Thanks & Regards,
Sanjoy Dey

Related

Foreach from array json data

I get an array in JSON format and I decode this data. I can access to single data by selecting e.g. echo $myArray[0]["name"];
However, I want to do a loop to iterate all names and prices from the array. Can you support me to find the bug in my code?
$url = "myurl";
$response = file_get_contents($url);
$myArray = json_decode($response, true);
foreach ($myArray as $product) {
echo $product->name . '<br>';
}
and here is a sample of the array:
[{
"id": 782,
"name": "Test Translation New",
"price": "1",
"image": {
"url": "xxx/image-2.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}, {
"id": 777,
"name": "Test Translation",
"price": "0",
"image": {
"url": "https:xxx/image-1.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}]
You are using json_decode(..., true), so the returned $myArray is an array, and all its sub items are all arrays.
<?php
$response = '
[{
"id": 782,
"name": "Test Translation New",
"price": "1",
"image": {
"url": "xxx/image-2.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}, {
"id": 777,
"name": "Test Translation",
"price": "0",
"image": {
"url": "https:xxx/image-1.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}]
';
$myArray = json_decode($response, true);
foreach ($myArray as $product) {
echo $product['name'] . "<br>\n";
}
Output:
Test Translation New<br>
Test Translation<br>
If the second argument of json_decode is given and it is true then the returned structure is an associative array. That being said you may print the names and prices like:
foreach ($myArray as $product) {
echo $product['name'] . ' - ' . $product['price'] . '<br>';
}
If the second argument of json_decode is given and it is true then the returned structure is an associative array. That being said you may print the names and prices like:
foreach ($myArray as $product) {
echo $product['name'];
echo (int) $product['price'];
}
or you can also do
foreach ($myArray as $product) {
echo "{$product['name']} - {$product['price']} <br />";
}

How to access multi-level json tree in PHP for database insertion

I am accessing an API where the JSON data is returned as below.
{
"name": "",
"count": 4,
"frequency": "",
"version": 3,
"newdata": true,
"lastrunstatus": "success",
"thisversionstatus": "success",
"thisversionrun": "",
"results": {
"collection": [{
"textlink": {
"href": "http://text1.com",
"text": "Text 1"
},
"index": 1,
"url": ""
}, {
"textlink": {
"href": "http://text2.com",
"text": "Text 2"
},
"index": 2,
"url": ""
}, {
"textlink": {
"href": "http://text3.com",
"text": "Text 3"
},
"index": 3,
"url": ""
}, {
"textlink": {
"href": "http://text4.com",
"text": "Text 4"
},
"index": 4,
"url": ""
}]
}}
As you can see the JSON tree returned has multi-step levels. I am wanting to be able to take some of the deeper levels, in PHP, and insert into a database.
Currently I am using this code to try and echo the data (once I am able to I can then work on inserting it to a database no problem)
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$results = json_decode($response, TRUE);
foreach($results as $item) {
echo $item->results[0]->collection[0]->textlink[0]->href;
echo "<br>";
echo $item->results->collection['href'];
echo "<br>";
echo $item->results->collection['text'];
}
?>
As you can see above I have tried several ways to access the deeper levels f data that are being displayed but with no avail.
I am currently getting errors of 'trying to get property of a non-object'. How is it possible to reach the data in this array?
try:
echo $results['results']['collection'][0]['textlink']['href'];
$obj = json_decode( $json, true ); foreach ( $obj['key'] as $key => $value ) { echo $value; }
foreach ($response['results']['collection'] as $textlink) {
$row = $textlink['textlink'];
echo $row['href'];
echo "<br>";
echo $row['text'];
echo "<br>";
}
you can do foreach like this, which loops only items in collection
I would suggest to do something like this (According to me, correct way to fetch results from API responses):
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$response = json_decode($response);
foreach($response->results->collection as $item) {
echo $item->textlink->href;
echo "<br>";
echo $item->textlink->text;
echo "<br>";
echo $item->index;
echo "<br>";
echo $item->url;
}
?>

Insert JSON values in MYSQL using PHP

I've this JSON string:
$json = '{
"bigprodlist": {
"prods": [
{
"code": 55,
"name": "Comix Book",
"link": "weblink"
},
{
"code": 85,
"name": "IT Book",
"link": "weblink"
},
{
"code": 95,
"name": "Manga Book",
"link": "weblink"
}
}
}';
I'd like to print every single entry on a webpage using php and then save these entries on a mysql db.
In the db there is already a "code", "name" and "link" field..
This is what I've tried without luck (to print the stuff on a page):
$obj = json_decode($json,true);
echo ($obj["bigprodlist"]["prods"][0]["name"]);
Thank you very much for the help
First, fix your JSON missing end bracket that makes JSON decoding fail (add the ] after the prods data ), then expand your echo statement with some foreach loops to get the data printed. This is only a simple example to get you on the right track:
foreach ($obj["bigprodlist"]["prods"] as $p):
echo "<div>";
foreach ($p as $name=>$value):
echo "<span>".$name.": ".$value."</span>";
endforeach;
echo "</div>";
endforeach;
You can then use the same loop procedure to get the data into your DB.
You need to use json_last_error(); http://no1.php.net/manual/en/function.json-last-error.php
Debugging:
$obj = json_decode($json,true);
var_dump($obj, json_last_error());
You are missing a ] :
$json = '{
"bigprodlist": {
"prods": [
{
"code": 55,
"name": "Comix Book",
"link": "weblink"
},
{
"code": 85,
"name": "IT Book",
"link": "weblink"
},
{
"code": 95,
"name": "Manga Book",
"link": "weblink"
}
] //missing!
}
}';
Where did you get json output?
It's invalid:
Parse error on line 18:
... } } }
----------------------^
Expecting ',', ']'
Check your json at http://jsonlint.com/

PHP and JSON using Yahoo Fantasy Sports API

I am trying to query and parse Yahoo fantasy sports data and show results in a friendly format.
Here is the JSON I get back from Yahoo from a successful request...
{
"fantasy_content": {
"xml:lang": "en-US",
"yahoo:uri": "\/fantasy\/v2\/users;use_login=1\/teams",
"users": {
"0": {
"user": [
{
"guid": "1234567890"
},
{
"teams": {
"0": {
"team": {
"team_key": "268.l.auto.t.209996",
"team_id": "209996",
"name": "Team Test",
"type": "auto"
}
},
"1": {
"team": {
"team_key": "273.l.auto.t.27741",
"team_id": "27741",
"name": "Team API",
"type": "auto"
}
},
"count": 2
}
}
]
},
"count": 1
},
"time": "29.808044433594ms",
"copyright": "Data provided by Yahoo! and STATS, LLC",
"refresh_rate": false
}
}
I am looking to get the team names from the teams array. I have tried using the following PHP code (among countless variations of it) to drill to the node I need but I am not having any luck.
$obj=json_decode($json);
$data = $obj->fantasy_content->users->user->teams->team;
foreach($data as $d){
echo 'name: ' . $d->name ; //prints php
}
I am hoping that someone might be able to provide a working example using the JSON above as I have clearly failed at this. Any help would be greatly appreciated.
Thanks in advance!
Try this
$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams;
foreach($data as $d){
echo 'name: ' . $d->team->name ; //prints php
}
EDIT
you can use the cout to loop through the names
$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams;
for($i = 0; $i < $data->count; $i++){
echo 'name: ' . $data->{$i}->team->name ; //prints php
}

How to extract Open Graph info from TXT file?

I have a TXT file containing some facebook Open Graph info like this:
{
"data": [
{
"name": "Avatar",
"category": "Movie",
"id": "82771544063",
"created_time": "2012-04-13T21:16:56+0000"
},
{
"name": "HappyDance",
"category": "Movie",
"id": "243564344063",
"created_time": "2012-04-13T21:16:56+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/me/likes?format=json&limit=5000&offset=5000&__after_id=5546653546361"
}
}
In PHP, I want to extract all the id numbers from the rows that show
"id": "XXXXXXXXXXXX",
The output should look like this:
I like 8277564344063
I like 243564344063
I started the following but I am getting an error:
<?php
$file_handle = fopen("raw.txt", "rb");
ob_start();
$text = file_get_contents('raw.txt');
$decode = json_decode($text);
print_r($decode);
$new_content = ob_get_clean();
file_put_contents("likes.txt", $new_content);
fclose($file_handle);
?>
The error is that my output is blank! What am I doing wrong?
Please help?
You don't have valid JSON.
The JSON Object below this line is valid JSON. I removed the comma after your last associative array within your "data" array. You shouldn't need a comma at the end of the array.
{
"data": [
{
"name": "Avatar",
"category": "Movie",
"id": "82771544063",
"created_time": "2012-04-13T21:16:56+0000"
},
{
"name": "HappyDance",
"category": "Movie",
"id": "243564344063",
"created_time": "2012-04-13T21:16:56+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/me/likes? format=json&limit=5000&offset=5000&__after_id=5546653546361"
}
}
Parse error on line 14:
... }, ], "paging": {
---------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
As I removed the comma from the non-valid JSON. I was able to get the result you wanted.
<?php
$json_object = file_get_contents('fb.json');
if(!$json_object) {
echo "oops, cant read the file";
}
// remap json_object
$json_object = json_decode($json_object,true);
foreach($json_object['data'] as $item) {
$items[] = "I like" . ' ' . $item['id'];
/* If you want to just echo " I like xyz" etc
* use echo "I like" . $item['id'];
*/
}
$list = implode(',',$items);
echo $list;
?>

Categories