So I am trying to create a jquery/ajax autocomplete form that uses the last.fm api to autocomplete the title of a song to whatever the user is typing, the problem im having is that I can not seem to get the last fm data to return in the proper json format. this is the format that my jquery plugin (link to autocomplete) would like returned:
{
"suggestions": [
{ "value": "United Arab Emirates", "data": "AE" },
{ "value": "United Kingdom", "data": "UK" },
{ "value": "United States", "data": "US" }
]
}
and here is essentially what im doing in my php script the returns the json to the autocomplete plugin:
$titleName = "what's my age";
$limit = 1;
$results = Track::search($titleName, $limit);
print_array($results);
echo "<ul>";
while ($title = $results->current()) {
echo $limit;
echo "<li><div>";
echo "Artist: " . $title->getArtist() . "<br>";
echo "Album: " . $title->getAlbum() . "<br>";
echo "Duration: " . $title->getDuration() . "<br>";
echo "getWiki: " . $title->getWiki() . "<br>";
echo "name: " . $title->getName() . "<br>";
echo "</div></li>";
$jsonArray['suggestions'] = array('Name'.$limit => $title->getName(), 'Artist'.$limit => $title->getArtist());
$limit++;
$title = $results->next();
}
echo "</ul>";
print_array($jsonArray);
echo json_encode($jsonArray);
the echo and print statments are just for testing, but this is what the json_encode is returning:
{"suggestions":{"Name2":"Blink vs. Jay-Z - what's my age again","Artist2":"Dj Tech1"}}
and this is what is being returned (via the echo testing):
1
Artist: Blink 1-82
Album:
Duration: 0
getWiki:
name: What's My Age Again?
2
Artist: Dj Tech1
Album:
Duration: 0
getWiki:
name: Blink vs. Jay-Z - what's my age again
so i know the code is working properly so is the sdk autocomplete etc. i also understand that am deleting the array in the while loop each time it loops through and i have not worked a fix out for that yet, but that issue aside, the json is not returning in the requested format and i can not seem to find the proper way to construct the array in order to get it in the proper format, any ideas?
$suggestionsArr['suggestions'] = [];
foreach (range(1,3) as $key => $value) {
array_push($suggestionsArr['suggestions'], ['name' => 'Song1', 'artist' => 'Artist1']);
}
echo json_encode($suggestionsArr);
Related
I'm toying with a small program that can pass a list of words to the Merriam-Webster API, and gets returned the definition, part of speech, sample sentence and so on.
The JSON string returned for each word by the API is as follows:
{
"meta": {
"id": "vase",
"uuid": "eb4f8388-84b2-4fd4-bfc8-2686a0222b73",
"src": "learners",
"section": "alpha",
"target": {
"tuuid": "60e7797e-fd75-43e1-a941-3def0963d822",
"tsrc": "collegiate"
},
"stems": [
"vase",
"vaselike",
"vases"
],
"app-shortdef": {
"hw": "vase",
"fl": "noun",
"def": ["{bc} a container that is used for holding flowers or for decoration"]
},
"offensive": false
},
"hwi": {
"hw": "vase",
"prs": [
{
"ipa": "ˈveɪs",
"pun": ",",
"sound": {"audio": "vase0002"}
},
{
"l": "British",
"ipa": "ˈvɑːz",
"sound": {"audio": "vase0003"}
}
]
},
"fl": "noun",
"ins": [
{
"il": "plural",
"if": "vas*es"
}
],
"gram": "count",
"def": [
{
"sseq": [
[
[
"sense",
{
"dt": [
[
"text",
"{bc}a container that is used for holding flowers or for decoration "
],
[
"vis",
[
{"t": "a beautiful Chinese {it}vase{/it}"},
{"t": "a {it}vase{/it} of roses"}
]
]
]
}
]
]
]
}
],
"shortdef": ["a container that is used for holding flowers or for decoration"]
}
]
The code I'm using to pull the information from the API is as follows:
<?php
$handle = fopen("inputfile.txt", "r");
if ($handle)
{
while (($line = fgets($handle)) !== false)
{
// process the line read.
//$json_new = grab_json_definition(trim($line), "collegiate", "0f3ee238-c219-472d-9079-df5ec8c0eb7d");
$json_new = grab_json_definition(trim($line) , "learners", "d300a82d-1f00-4f09-ac62-7ab37be796e8");
$data = json_decode($json_new, true);
echo "Word: " . $data[0]['meta']['id'] . "<br/>";
echo "IPA: " . $data[0]['hwi']['prs'][0][ipa] . "<br/>";
echo "Part of Speech: " . $data[0]['fl'] . "<br/>";
echo "Definition: " . $data[0]['shortdef'][0] . "<br/>";
echo "Sentence: " . $data[0]['def'][0]['sseq'][0][0][0] . "<br/>";
}
fclose($handle);
}
else
{
// error opening the file.
}
function grab_json_definition($word, $ref, $key)
{
$uri = "https://www.dictionaryapi.com/api/v3/references/" . urlencode($ref) . "/json/" . urlencode($word) . "?key=" . urlencode($key);
return file_get_contents($uri);
};
?>
I can easily navigate through to get the Word, Definition and so on, but I can't navigate down to "t" to get the sample sentences. I'm sure it's something basic but I can't figure it out. Any help would be appreciated.
First, your JSON example is broken, I believe it is missing a [ in the beginning.
Now, Here is an example, where I load the contents of the file, json_decode your SINGLE example. Note that I am not adding a foreach loop or while loop, but I am getting all of the attributes you are aiming for:
<?php
$f = file_get_contents('inputfile.txt');
$data = json_decode($f);
print_r($data);
echo "Word: " . $data[0]->meta->id . "<br/>";
echo "IPA: " . $data[0]->hwi->prs[0]->ipa . "<br/>";
echo "Part of Speech: " . $data[0]->fl . "<br/>";
echo "Definition: " . $data[0]->shortdef[0] . "<br/>";
echo "Sentence: " . $data[0]->def[0]->sseq[0][0][0] . "<br/>";
echo "T1: " . $data[0]->def[0]->sseq[0][0][1]->dt[1][1][0]->t . "<br/>"; // those can also be in foreach loop, I am just showing the basic example of accessing the attributes
echo "T2: " . $data[0]->def[0]->sseq[0][0][1]->dt[1][1][1]->t . "<br/>";
You can extend this code, or modify yours to add while/foreach loops... as you need them..
I am trying to read a json file in php, i can retrieve the root parts of the file, however whatever i try, i can not read the innner parts(child) of the json file, any help would be great
here is the json file
{
"orderId":"112-1567223-2156269x",
"legacyOrderItemId":"0218943273x4778",
"orderItemId":"2068965x7409001",
"asin":"B01K9RxxB0GQ",
"title":"xippro decs",
"merchantId":"A3H7UYG3T9xx6JDM",
"quantity":1,
"version3.0":{
"customizationInfo":{
"surfaces":[
{
"name":"Surface 1",
"areas":[
{
"colorName":"White",
"fontFamily":"Coppergate Bold",
"Position":{
"x":13,
"y":218
},
"name":"Line 1",
"Dimensions":{
"width":382,
"height":53
},
"label":"Your Text Here",
"fill":"#FFFFFF",
"customizationType":"TextPrinting",
"text":"Ruth's"
},
{
"colorName":"White",
"fontFamily":"Coppergate Bold",
"Position":{
"x":144,
"y":258
},
"name":"Customization 2",
"Dimensions":{
"width":119,
"height":17
},
"label":"Date (EST)",
"fill":"#FFFFFF",
"customizationType":"TextPrinting",
"text":"1969"
}
]
}
]
}
},
"customizationInfo":{
"aspects":[
{
"title":"Your Text Here",
"text":{
"value":"Ruth's"
},
"font":{
"value":"Coppergate Bold"
},
"color":{
"value":"#FFFFFF"
}
},
{
"title":"Date (EST)",
"text":{
"value":"1969"
},
"font":{
"value":"Coppergate Bold"
},
"color":{
"value":"#FFFFFF"
}
}
]
},
"version":"2.0"
}
and my php code is below
<?php
$file = file_get_contents('16532135318050.json', true);
$character = json_decode($file,false,400);
//print_r ($character);
echo $character->orderId . "<Br>";
echo $character->legacyOrderItemId . "<Br>";
echo $character->orderItemId . "<Br>";
echo $character->asin . "<Br>";
echo $character->merchantId . "<Br>";
echo $character->quantity . "<Br>";
echo $character->version3.0->customizationInfo->surfaces->areas[0]->colorName; // does not work
echo $character->version3.0->customizationInfo->surfaces->areas->colorName; // does not work
?>
Two issues:
version3.0 isn't a valid identifier - you should use {"version3.0"} instead.
surfaces is an array, so you should use surfaces[0]
this might work
$character->{"version3.0"}->customizationInfo->surfaces[0]->areas[0]->colorName
The reason it doesn't work is because $character->version3.0->customizationInfo->surfaces is an array and needs to be dereferenced accordingly:
$character->{'version3.0'}->customizationInfo->surfaces[0]->areas[0]->colorName
This is the JSON data I get from our ticket-system. I would like to parse it with PHP and save the data in a database to create statistics and a dashboard so everyone can see how many tickets are open and the latest closed tickets.
I can read some of the data but not everything.
{
"address":"belgium",
"workers":{
"peter":{
"worker":"peter",
"open_close_time":"45.6 T/h",
"closed_tickets":841,
"open_tickets":7,
"last_checkin":1498768133,
"days_too_late":0
},
"mark":{
"worker":"mark",
"open_close_time":"45.9 T/h",
"closed_tickets":764,
"open_tickets":2,
"last_checkin":1498768189,
"days_too_late":0
},
"walter":{
"worker":"walter",
"open_close_time":"20.0 T/h",
"closed_tickets":595,
"open_tickets":4,
"last_checkin":1498767862,
"days_too_late":0
}
},
"total_tickets":2213,
"tickets":[
{
"id":2906444760,
"client":"297",
"processed":0
},
{
"id":2260,
"client":"121",
"processed":0
},
{
"id":2424,
"client":"45",
"processed":0
}
],
"last_closed_tickets":[
{
"id":2259,
"client":"341",
"closed_on":"2017-06-25T10:11:00.000Z"
},
{
"id":2258,
"client":"48",
"closed_on":"2017-06-20T18:37:03.000Z"
}
],
"settings":{
"address":"belgium",
"email":"",
"daily_stats":0
},
"open_close_time":"161.1 T/h",
"avgopen_close_time":123298,
"ticket_time":"27.1 T/h",
"stats":{
"time":1498768200087,
"newest_ticket":1498768189000,
"closed_tickets":2200,
"open_tickets":13,
"active_workers":3
},
"avg_paid_tickets":64.55,
"avg_afterservice_tickets":35.45
}
This is the PHP code I tried to get the names of the worker but this doesn't work.
<?php
$string = file_get_contents("example.json");
$json = json_decode($string, true);
echo $json['address'];
foreach($json->workers->new as $entry) {
echo $entry->worker;
}
?>
If I try it like here below it works but then I've got to change the code everytime another employee starts.
echo $json['workers']['mark']['closed_tickets'];
<?php
$string = file_get_contents("example.json");
$json = json_decode($string, true);
foreach($json['workers'] as $entry){
echo $entry['worker'] . " has " . $entry['open_tickets'] . " tickets" . "\n";
}
?>
I am having some issues trying to pull some data from a multi-level json url. I can get everything else except for a certain nested section.
{
"name": "NewNationsPnW",
"count": 10,
"frequency": "Every 15 mins",
"version": 31,
"newdata": false,
"lastrunstatus": "success",
"thisversionstatus": "success",
"nextrun": "Wed Jan 13 2016 22:57:30 GMT+0000 (UTC)",
"thisversionrun": "Wed Jan 13 2016 22:42:30 GMT+0000 (UTC)",
"results": {
"collection1": [
{
"Nation": {
"href": "https:\/\/politicsandwar.com\/nation\/id=30953",
"text": "Renegade States"
},
"Founded": "01\/13\/2016",
"Alliance": "None",
"Continent": "North America",
"property7": "",
"index": 1,
"url": "https:\/\/politicsandwar.com\/nations\/"
}
]
}
}
The following code works to display that nested area but I would like to get it to individual outputs.
$request = "https://www.kimonolabs.com/api/4p7k02r0?apikey=qAnUSnSVi8B17hie7xbPh9ijikNLzBzk";
$response = file_get_contents($request);
$json = json_decode($response, true);
//echo '<pre>'; print_r($results);
foreach($json['results']['collection1'] as $stat) {
foreach($stat['Nation'] as $stat1) {
echo $stat1;
}
if($stat['Alliance'] == 'None') {
echo $stat['Founded'] . " - " . $stat['Alliance'] . " - " . $stat['Continent'] . "<br />";
}
}
I have tried the following
foreach($json['results']['collection1'] as $stat) {
foreach($stat['Nation'] as $stat1) {
echo $stat1['text'];
echo $stat1['href'];
}
if($stat['Alliance'] == 'None') {
echo $stat['Founded'] . " - " . $stat['Alliance'] . " - " . $stat['Continent'] . "<br />";
}
}
but I get
Illegal string offset 'text' in parse.php on line 10
Illegal string offset 'href' in parse.php on line 11
As well as it only displays
hhRR01/13/2016 - None - North America
hhFFhhDD01/13/2016 - None - Asia
I am sure I am doing something that is simple to fix but being a rookie, I am messing it all up.
Your nested loop is unnecessary, and the cause of your errors:
foreach($json['results']['collection1'] as $stat) {
echo $stat['nation']['text'];
echo $stat['nation']['href'];
}
There is no need to convert a perfectly good JSON object data structure to an array.
<?php
$request = "https://www.kimonolabs.com/api/4p7k02r0?apikey=qAnUSnSVi8B17hie7xbPh9ijikNLzBzk";
$response = file_get_contents($request);
$j = json_decode($response );
foreach ($j->results->collection1 as $collection1 ) {
echo $collection1->Nation->href;
echo $collection1->Nation->text;
if($collection1->Alliance == 'None') {
echo sprintf("%s - %s - %s<br />",
$collection1->Founded,
$collection1->Alliance,
$collection1->Continent
);
}
}
I'm working on json source from wunderground.com. As the example code displayed in the document. I can adjust and work out for some simple format. But I'm stuck with this one. I tried to googled every where but there's no solution.
Here's the sample codes:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>
Well, I need some information like "Cedar Rapids" out of pws/station :
"pws": {
"station": [
{
"neighborhood":"Ellis Park Time Check",
"city":"Cedar Rapids",
"state":"IA",
"country":"US",
"id":"KIACEDAR22",
"lat":41.981174,
"lon":-91.682632,
"distance_km":2,
"distance_mi":1
}
]
}
(You can get all code by clicking this : http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json )
Now the questions are:
What is this data called? (array, array in array?)
How could I pull this data out of the line?
Regards,
station is an array within the pws object.
To get the data, you can do something like this:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (strcmp($station->{'id'}, "KIACEDAR22") == 0)
{
echo "Neighborhood: " . $station->{'neighborhood'} . "\n";
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
break;
}
}
?>
Output:
Current temperature in Cedar Rapids is: 38.5
Neighborhood: Ellis Park Time Check
City: Cedar Rapids
State: IA
Latitude: 41.981174
Longitude: -91.682632