Formatting datetime in JSON script - javascript

This is my PHP/JSON script from localhost:
http://www16.zippyshare.com/v/6486125/file.html is the link if you need to download the PHP files to edit them in your answers if you want. (The link to the JSON file is mentioned in large-schedule.js in the file. Instructions on usage provided).
It partially works (as in the file echoes the data).
This is the code:
<?
header('Content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
$link = mysql_pconnect("localhost", "test", "test") or die("Could not connect");
mysql_select_db("radiostations") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM radio1r1");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"success":true,"error":"","data":{"schedule":['.json_encode($arr).'}';
echo isset($_GET['callback'])
? "{$_GET['callback']}($json)"
: $json;
However, I cannot get the contents of the fields startminutes and endminutes (stored as DATETIME) to display as 01/02/2013 00:00:00 within the JSON, in order to display them as
01/02/\2013 00:00:00
The fields I have are in the SQL file above.
As a PHP/JSON file the code works at a basic level; I can do callbacks well, but is there an easier way to get success true error data to display without manually putting it in?
As for the query string callback, I intend to do it so it has these 4 stations with different results from the MySQL tables:
Radio 1
Anytown FM
Big City FM
so the callback would look like
http://127.0.0.1/phpradiostation/radioschedule-json.php?callback=?&name=Anytown+FM
or
http://127.0.0.1/phpradiostation/radioschedule-json.php?callback=?&name=Big+City+FM
I have got it halfway there, with regard to the JSON but it displays a blank page despite there being data in the database!
PHP info: I'm using 5.4.1.0, on MAMP, OS X Mavericks, if that's relevant.
Basically, what I am asking is for help on actually getting it to display the data in the javascript.
Any help is appreciated!

As far as I can understand,
1st thing I notice is you are using json_encode in a wrong way. What you have to do is create a multi dimentional array and use json_encode to convert the particular array to JSON rather than manually doing it.
Answer to your question is yes JSON content should be escaped when they are passed. That why it shows as 01/02/\2013 00:00:00. What you have to do is decode the JSON data at the client-side. See the below two links.
How to JSON decode array elements in JavaScript?
Parse JSON in JavaScript?
Also use jsonlint to validate your JSON data.

Related

how to save tensorflow save model multiple files in php

I have developed a neural network model with tensorflow. I want to save weights of my model on each time they update. So i though of updating a file on the server every time it learns. but the documentation on tensorflow js website on saving model using http server is really confusing. So i did some research and found some code. Still it is not working. I know i am missing the "multipart/form-data" and fact that there are two files, "The body consist of two files, with filenames model.json and model.weights.bin". Could not find anything that could help me. link to tensorflow documentation!
javascript to save
model.save('http://example.com/save.php');
save.php
<?php
$putdata = fopen("php://input", "r");
$fname = "weights.json";
$file = fopen("../static/" .$fname, 'w');
while ($data = fread($putdata, 1024)){
fwrite($file, $data);
}
fclose($file);
fclose($putdata);
?>
http://php.net/manual/en/function.file-put-contents.php
I don't see the input section with php stdin. This makes me feel like the connection isn't sending a stream like a socket connection, but rather a standard HTTP payload with a body attribute. But wait, theirs caveats. If it is a JSON payload you'll need the second two lines (like you had in your code, but not as a resource). The first two are my guess as to what may be going on. Remember you can debug through your browsers console to see the data payload, request method, ect...
$data = '<pre>' . json_encode($_POST) . '</pre>';
file_put_contents('stdPost.html', $data);
$data = file_get_contents('php://input');
file_put_contents('stdInput.json', $data);

How to programmatically edit JSON-LD in 'script' elements?

I have several HTML files on my server that contain JSON-LD script elements. I'm looking for an easy way to update specific elements without physically going into each file, changing the code, and re-saving it.
Specifically, I would like to programmatically loop through each file, find the datePosted property and update its value to the current date, then save the file on my server.
I'm mostly comfortable using PHP and I've done something like this with HTML files, but never tried updating JSON-LD before.
Wondering if anyone knows how to do this with JavaScript or PHP. If not could someone point me in the right direction of a good parser that works with JSON-LD?
Sample JSON-LD:
{
"#context": "http://schema.org",
"#type": "JobPosting",
"datePosted": "2018-01-23"
}
This was pretty easy, just needed to use json_decode and json_encode to make it work:
$file = "file-path-to-json-ld";
$string = file_get_contents($file); // pulls the file
$json = json_decode($string, true); //creates a searchable array
var_dump($json); // just to see what elements and values are in the decoded array
$json['element-name-in-json-ld'] = "new-value-for-element"; //change any value you like
$updatedString = json_encode($json, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); //re-encode backing into json
file_put_contents($file, $updatedString); // put file back

Get Data from Mysql using (PHP) and send it to typescript/javascript using JSON

I have got data from mysql in php, and i want to send it to typescript using JSON. but when load the php page. nothing showed in the screen. It always shows a blank page.
$select ="SELECT * from `filiere`";
$run = mysqli_query($connect, $select);
$temp = array();
while($row=mysqli_fetch_row($run)) {
$temp[] = $row;
}
echo json_encode($temp);
from the code, it should show the data in json format.
what it is the problem?
I think i've understood where is my error.
You are all right. i have some data with frensh letters like ('é', 'ù'..). I think that was the problem.
Thank you all
In PHP, an unexpeted blank page usually means some kind of error + error reporting turned off.
Try to turn error reporting on
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(E_ALL);
EDIT #1:
Based on the comments, it seems that json_encode() fails, so returns false (echoing false will result in a blank page).
The json_last_error() and/or json_last_error_msg() functions should be used to find the error.
EDIT #2:
The first argument of json_encode() must hold only UTF-8 encoded strings.
did you set endpoint content-type on php ?
header('Content-Type: application/json');

What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing

THE QUESTION
What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing.
I have a MYSQL database and have a PHP script that creates an indexed row array of the database information.
Now that this information is within the array i am comfortable about echoing this data on screen from within PHP.
i.e.
echo $lastplayed[1]['artist'];
My next step is to take the array into JavaScript so that i can use the variable information to display data on screen, make calculations and create an Ajax timer that looks for a value from a variable and refreshes the page..
Its basically a internet radio station that will display what is and has been played and when a counter reaches zero will refresh the page. (the counter being time left of a song)
I could echo each variable into a separate PHP script and then use JavaScript to call each of those PHP scripts that contain the different variables (This seems long-winded) AND puts unnecessary request strain on the MYSQL server
**I really feel that there must be a better way of transferring and handling the data, surely there must be some type of bridge between PHP and JavaScript, should i be looking into JSON ?
So my end result is to be able to take an indexed array from PHP, transfer this array into JavaScript and be able to call on different variables from within the array using indexing (i.e call the variable that resides in result 3 column 3)
And while this is happening i will be using separate PHP and JavaScript files...
Here is my code for the PHP part.
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime))
?>
Any thoughts on this would be greatly appreciated and thanks so much for your time.
Justin.
PROGRESS:
Thanks for the comments, i really need to take a JavaScript course at this point...
Now i have created a new output.PHP file that does the following
<?php
require_once("dblastplayedarray.php");
echo json_encode($lastplayed);
?>
So this file now echo's out the data i need in a JSON format from my array $lastplayed.
#VCNinc you say that i now can use the following code to take the data into JavaScript
<script>
var array = <?=json_encode($lastplayed)?>;
</script>
Please could you detail where i put the path information in this code so that the program knows where to look for the .PHP file output.php
Am i doing this right.. should i be printing the data into another .PHP file and then use your code to take the array into JavaScript..
Thanks
Justin.
JSON is the bridge!
You can "export" the variable to a json string and print on the output:
echo json_encode($lastplayed);
TIP: if the php file is used to show a html GUI AND you still want output a JSON too, you can create a GET variable like "&json=1" and, before output your HTML GUI, you do a IF. This way tou can use the same php file to output a GUI and the JSON. WHen you do the request via ajax, you call using the "&json=1".
if(isset($_GET['json']) && $_GET['json']==1){
echo json_encode($lastplayed);
exit;
}
Then, use AJAX to download this JSON string by calling your php script.
$.getJSON(url, function (json) {
//here the 'json' variable will be the array
//so you can interact on it if you want
$.each( json, function( key, value ) {
alert( key + ": " + value ); //here you can do anything you want
});
});
If you have a PHP array $array, you can easily export it into JavaScript like this:
<script>
var array = <?=json_encode($array)?>;
</script>
(and from that point you can manipulate it as JSON...)

How to import external JSON and display in php

I have a WordPress site for people with Multiple Sclerosis and to assist them in finding current clinical trials that are recruiting participants I have an external JSON file of search results I want to display on my site.
Here is a sample output from the JSON:
{"intervention_browse":{"mesh_term":["Copolymer 1"]},"id_info":{"nct_id":"NCT00004814"},"sponsors":{"collaborator":[{"agency":"University of Maryland","agency_class":"Other"}],"lead_sponsor":{"agency":"National Center for Research Resources (NCRR)","agency_class":"NIH"}},"overall_status":"Completed","condition_browse":{"mesh_term":["Multiple Sclerosis","Sclerosis","Multiple Sclerosis, Relapsing-Remitting"]}}
What would be the best way to do this? An example using cURL or JSON_decode would be nice. (I only know enough to get myself into trouble, so assume I'm in kindergarten please. :) )
Since it's going into a WordPress site, should I use PHP or javascript or a combination of both for displaying it?
Once I get the information to display on my site I have no problem styling it with css. Getting it on the page is my main issue.
I have installed a plugin that allows me to add php directly into any page or post using shortcodes, but what code to put there is what's holding me up.
Here is the JSON file:http://api.lillycoi.com/v1/trials/search.json?query=cond:%22Multiple+Sclerosis%2C+Relapsing-Remitting%22&fields=id_info.nct_id,condition_browse,sponsors,intervention_browse,overall_status&limit=1000
You can follow it:
<?php
$url = "http://api.lillycoi.com/v1/trials/search.json?query=cond:%22Multiple+Sclerosis%2C+Relapsing-Remitting%22&fields=id_info.nct_id,condition_browse,sponsors,intervention_browse,overall_status&limit=1000";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
?>
You can use var_dump or print_r to know what's in your data :
<?php var_dump($data); ?>
or
<?php print_r($data); ?>
The TRUE returns an array instead of an object.

Categories

Resources