{
"employees": [{
"name": "Chicken Shawarma",
"price": "510.00",
"nutrients": "A
B "
}]
}
this is the my json response , In My app i setup a two line record for "nutrients". Ex :
A
B
this vale saved in database without any issue (My SQL), now i want display the "nutrients" data as a two line record. but its displaying below error
SyntaxError: unterminated string literal
if you have any idea please share with me.
this is the my server side code
if ($itemInfo->num_rows() == 1) {
$row = $itemInfo->row_array();
$json_arr = $_GET['callback'] . '(' .
"{'name' : '" . $row['name'] . "',"
. "'nutrients' : '" . $row['nutrients'] . "',"
. "'img' : '" . $row['img'] . "'}" . ')';
} else {
$json_arr = json_encode(array('status' => 'N'));
}
echo $json_arr;
this is the my client side code
$http.jsonp(full_url).success(function (data) {
$scope.item = data ;
});
Your main problem is making a JSON response by concatenating strings. In such case you miss required encodings/escaping and so on. So, first of all you should create an associative array and then do $json_arr = $_GET['callback'].'('.json_encode($your_json_like_array).')'; exactly like in the else clause.
Resulting code should look like this:
$json_arr = array(
'name' => $row['name'],
...,
'nutrients' => $row['nutrients']
);
$json_arr = $_GET['callback'].'('.json_encode($json_arr).')';
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..
iam trying to show multiple Graphs in one diagram. The datasource is a MySQL database which is connected via PHP.
My Problem: I cant figure out how to add the data to the RGraph Script. I managed to show one graph via PHP, bt i cant add a seconde one.
This is how i succsessfully get the Data (After connecting to the Database ofc.):
Important!: (At least i guess it is) i have two different cases, in one Case the return Data is a single Number (eg: "2") in my seconde case it is an array of 52 different numbers.
$1 = mysql_query("SELECT * FROM Table WHERE spalte1 ='XX' AND spalte2 ='XX' ORDER BY Datum DESC Limit 1");
if ($1) {
$labels = array();
$data = array();
while ($row = mysql_fetch_assoc($1)) {
$labels[] = $row["datum"];
$2[] = $row["max"];
}
// Now you can aggregate all the data into one string
$2_string = "[" . join(", ", $2) . "]";
$labels_string = "['" . join("', '", $labels) . "']";
}
else
{
print('MySQL query failed with error: ' . mysql_error());
}
This is how i draw the Graph:
<canvas id="cvs" width="1200" height="250">[Browser not supported]</canvas>
<script>
//window.onload = function ()
//{
new RGraph.Line({
id:'cvs',
data:[<?php print($2_string) ?>],
options: {
colors:['#B71A1A'],
backgroundGrid: true,
//xaxisLabels: [<?php print($labels_string) ?>],
//xaxisLabelsAngle: 25,
xaxis: true,
yaxis: true,
yaxisScale: true,
yaxisScaleUnitsPost:'%',
yaxisScaleMax: 100,
title: 'XX',
textAccessible: true,
key: ['XX'],
keyPosition: 'margin',
keyPositionX: 25,
}
}).draw();
But how can i add a seconde graph into this diagram? All the Demos say something like:
data = [[1,2,3],[4,5,6]]
So i tryed different versions (just one example):
data = [[<?php print($1_string) ?>],[<?php print($2_string) ?>]]
Hopefully someone has an Idea ... :)
Thx for every try :)
Here is what I sent Simon via email
<?php
$1_data = 5;
$2_data = array(2,3,8 4,6,8,6,9,8,7,5,8);
// Make JavaScript arrays out of the above number and PHP array
// also making an array of two numbers out of the single number
$1_string = '[' . join(',', array($1_data, $1_data) . ']';
$2_string = '[' . join(',', $2_data) . ']';
?>
<canvas id="cvs" width="1200" height="250">[Browser not supported]</canvas>
<script>
new RGraph.Line({
id:'cvs',
data:[
<?php print($1_string) ?>,
<?php print($2_string) ?>
],
options: {
}
}).draw();
</script>
I had been following this guide to create an app using two different APIs but the guide is old and so one of the APIs does not work like it did in the guide. I am trying to grab coordinates from google geocoding API and stick them into Places for Web. I am new to PHP, so I was following the guide's example to traverse a JSON object but have been stuck all night trying to get it to work.
Here is the JSON object from the place search API
{
"html_attributions":[ ],
"results":[
{
"geometry":{ },
"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id":"d4b0fb0f7bf5b2ea7df896a0c120a68efae039cf",
"name":"Guadalajara Mexican Grill & Cantina",
"opening_hours":{ },
"photos":[
{
"height":2952,
"html_attributions":[ ],
"photo_reference":"CmRaAAAAfO4JKUaO8vCFM2dcu5LMu4mA4_HXQGJ1FyAnyJUre_kD6VOWiQj7tBEECx4AAct5AORIKipSYWg-Zprjlf8o-SFd7mBRGMXMVMwodFZ5KMLwPYPUhBnTTehGPkb9275pEhCkAqMwfmK29vYenk1wdwFvGhSIHR8ch6FONc99tGn4rVnesbuteg",
"width":5248
}
],
"place_id":"ChIJ27es4SWa3IARcvjmt3xL2Aw",
"price_level":2,
"rating":4.4,
"reference":"CmRRAAAA7Rx-l7juDX-1or5dfpK6qFcZ0trZ9cUNEUtKP2ziqHb2MhOE6egs-msJ2OdFKEuHhuNe-3Yk6yxUYwxCBqhDT3ci8pYZI4xYhPGyyDgDenbEU_8k84JiEtCGvj4bdIR0EhDR2Pqte5_kDUcCC9PJFVknGhQomvD4d7NBIhCFxI4i2iEc0w9UiA",
"scope":"GOOGLE",
"types":[ ],
"vicinity":"105 North Main Street, Lake Elsinore"
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"status":"OK"
}
I am trying to grab all the photo references into an array maybe?, and then plug them into google's Place Photos API. Here is my attempt at that:
UPDATE
<?php
if(!empty($_GET["location"])){
//$API_key = "";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($_GET['location']) .
'&key=';
$maps_json = file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
'location=$lat,$lng' .
'&radius=1500' .
'&rankby=distance' .
'&key=';
$places_json = file_get_contents($places_url);
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array as $item) {
var_dump($places_array );
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>What is Here?</title>
</head>
<body>
<h1>Type in a location</h1>
<p>This program will display pictures of places to go in that area</p>
<form action ="">
<input type ="text" name ="location"/>
<button type ="submit">Go!</button>
</form>
<br/>
<?php
echo "$lat $lng";
?>
Just can't seem to get the foreach loop to do anything
the invalid request means wrong url or bad parameters
if $lat and $lng are variables then the interpolation wont work with single quotes try using double quotes like this
"location=$lat,$lng"
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key=mykey';
you should remove radius or distance you cant get both its on the docs
https://developers.google.com/places/web-service/search?hl=en-419
here is my modified code that works on localhost please notice the $contextOptions you should not copy this on your code this is a workaround to make file_get_contents work on my machine
after that the foreach should be easy since is only an array look at the code
$thelocation = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";
$thekey = "someapikey";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($thelocation) .
'&key=' . $thekey;
$contextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$maps_json = file_get_contents($maps_url, 0, stream_context_create($contextOptions));// file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key='.$thekey;
//https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&rankby=distance&key=
$places_json = file_get_contents($places_url,0, stream_context_create($contextOptions));
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array["results"] as $item) {
echo $item["name"]."<br>";
}
}
this prints....easy
AVEonline.co
KRAV MAGA GLOBAL WORLD MAP
Mark Carvalho
Amyan
Moving the Planet
Sosta in Camper
NosCode
GLOBAL BUZZ
OptiClean
JI-SU TELECOM
Reel Thrillz
Clío Reconstrucción Histórica
AprimTek
Hayjayshop
NHAV
gitanos.cat
Being Digitall
Directory+
AdExperts
Optical Spectroscopy and Nanomaterials Group
The $lat,$lng variables or the API call is your first problem, and the foreach loop is the second.
The json_decode($someJSON, true); creates an associative array from your json, so you can't use the -> arrows, those are for the objects. More about this.
There's no $item->photo_reference, use:
$results = $places_array["results"];
foreach ($results as $item) {
echo $item["photos"]["photo_reference"];
}
I'm trying to extract the main table from a website, convert it to JSON, but the tables before the one I want are obstructing the code I'm using. The code I'm using:
<?php
$singles_chart_url = 'http://www.mediabase.com/mmrweb/allaboutcountry/Charts.asp?format=C1R';
// Get the mode from the user:
$mode = $_GET['chart'];
// This is an array of elements to remove from the content before stripping it:
$newlines = array("\t", "\n", "\r", "\x20\x20", "\0", "\x0B");
switch($mode)
{
// They want the Singles chart, or haven't specified what they want:
case 'singles':
case '':
default:
$content = file_get_contents($singles_chart_url);
$start_search = '<table width="100%" border="0" cellpadding="2" cellspacing="2">';
break;
}
$content = str_replace($newlines, "", html_entity_decode($content));
$scrape_start = strpos($content, $start_search);
$scrape_end = strpos($content, '</table>', $scrape_start);
$the_table = substr($content, $scrape_start, ($scrape_end - $scrape_start));
// Now loop through the rows and get the data we need:
preg_match_all("|<tr(.*)</tr>|U", $the_table, $rows);
// Set the heading so we can output nice XML:
switch($_REQUEST['format'])
{
case 'json':
default:
header('Content-type: application/json');
$count = 0;
foreach($rows[0] as $row)
{
// Check it's OK:
if(!strpos($row, '<th'))
{
// Get the cells:
preg_match_all("|<td(.*)</td>|U", $row, $cells);
$cells = $cells[0];
$position = strip_tags($cells[0]);
$plus = strip_tags($cells[1]);
$artist = strip_tags($cells[2]);
$weeks = strip_tags($cells[3]);
echo "\n\t\t" . '{';
echo "\n\t\t\t" . '"position" : "' . $position . '", ';
echo "\n\t\t\t" . '"plus" : "' . $plus . '", ';
echo "\n\t\t\t" . '"artist" : "' . $artist . '", ';
echo "\n\t\t\t" . '"noWeeks" : "' . $weeks . '" ';
echo ($count != (count($rows[0]) - 2)) ? "\n\t\t" . '}, ' : "\n\t\t" . '}';
$count++;
}
}
echo "\n\t" . ']';
echo "\n" . '}';
break;
}?>
The website I'm trying to scrape. The goal is to retrieve json results of the table beginning after LW, TW, Artist, Title, etc. The above returns:
{
"chartDate" : "",
"retrieved" : "1444101246",
"entries" :
[
{
"position" : "7 DayCharts",
"plus" : "Country Past 7 Days -by Overall Rank Return to Main Menu ",
"artist" : " ",
"noWeeks" : "",
"peak" : "",
"points" : "",
"increase" : "",
"us" : ""
},
]
}
instead of
{
"chartDate" : "",
"retrieved" : "1444101246",
"entries" :
[
{
"position" : "2",
"plus" : "1",
"artist" : "KENNY CHESNEY",
"noWeeks" : "Save It For A Rainy"", etc . etc.
},
]
}
What could I add to the code above to retrieve that table?
Update
The problem is the match pattern.
After following statement,
$content = str_replace($newlines, "", html_entity_decode($content));
Some characters are replace or removed, such as " and Some tags are being in UPPERCASE. Hence you are always getting 0 as strpos for $scrape_start no matter what $start_search contains.
So you have to search like,
$start_search ='<TBODY>';
Working code on PhpFiddle
I have the following jquery statement:
$("#add").click(
function(event){
var groupName = $("#groupName option:selected").text();
var studentsToAdd = $('select#mainList').val();
var mode = "exempt";
$.post(
"addToList.php",
{ studentsToAdd: studentsToAdd, mode: mode },
function(data) {
$('#groupList').html(data[exemptList]);
$('#mainList').html(data[nonexemptList]);
}
);
});
With the following php code:
$studentsToAdd = $_REQUEST['studentsToAdd'];
$arrayLength = count($studentsToAdd);
$exemptList = "";
$nonexemptList = "";
for ($i=0;$i<$arrayLength;$i++){
$result = mysql_query("UPDATE students SET exempt=1 WHERE id = '$studentsToAdd[$i]'");
}
$result = mysql_query("SELECT * from students WHERE exempt = 1");
while($row = mysql_fetch_array($result))
{
$exemptList = $exemptList . "<option value=\"" . $row['id'] . "\">" . $row['last'] . ", " . $row['first'] . "</option>";
}
$result = mysql_query("SELECT * from students WHERE exempt = 0");
while($row = mysql_fetch_array($result))
{
$nonexemptList = $nonexemptList . "<option value=\"" . $row['id'] . "\">" . $row['last'] . ", " . $row['first'] . "</option>";
}
$data = array(
'exemptList' => $exemptList,
'nonexemptList' => $nonexemptList
);
echo json_encode($data);
I am trying to update both mainList and exemptList select elements with the single jQuery .post. It is not working. Thoughts?
If your php code is in another page or in a function, which you haven't mentioned, return $data instead of return json_encode($data) should work and leave it as an array. Otherwise you are getting a json string back, from json_encode(), which you need to parse into a javascript object, so try:
var decoded = $.parseJSON(data);
$('#groupList').html(decoded.exemptList);
$('#mainList').html(decoded.nonexemptList);
At least from what i can tell at first glance and 11 pm.
Edit: You can always try console.log(data) with Firefox Firebug plugin and see what you are getting from the server and then see if you need to decode what you are getting, change how you write the array or quotes or whatever.
A possible solution is to decode the JSON object when it is returned. Additionally, the stuff inside the [] needs to have quotes around it:
function(data) {
var json = JSON.parse(data);
$('#groupList').html(json["exemptList"]);
$('#mainList').html(json["nonexemptList"]);
}
Also, maybe try $.ajax, and set dataType to json (even though the default is intelligent guess, which should work anyway since the PHP is sending a JSON object.)
Maybe you could try:
function(data) {
$('#groupList').html(data["exemptList"]);
$('#mainList').html(data["nonexemptList"]);
}
exemptList and nonexemptList were probably treated as variables instead of names.