How to import external JSON and display in php - javascript

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.

Related

Use PHP to embed JSON for use by Javascript

I'm working on using React (javascript) inside a WordPress plugin but my plugin requires some data retrieved from the database. I could probably retrieve the required data in javascript using jquery or an API call, but since the data will be static, it seemed more efficient to embed the data using php prior to rendering the DOM element with javascript.
I tried the following, but the <script> tag containing the json never appears in the DOM.
<?php
$events = \Civi\Api4\Event::get()
->addSelect('*')
->addOrderBy('start_date', 'ASC')
->setLimit(25)
->execute();
echo "<script type=\"application/json\" id=\"eventList\">";
echo json_encode($events);
echo "</script>";
?>
<div id="civi-react-events">
<h2>Loading...</h2>
</div>
Update
It turns out the code above works. It turned out to be a cache issue. Ctrl-Refresh is your friend.
Thank you to those who took the time to respond.
Sometimes, json_encode returns tags, texts, etc. with a wrong format. It may lead to break the script tag To ensure the json is fine to use, use the json_encode flags. I personally recommend using the following flags:
<?php
$jsonExportConst = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK;
$eventsJson = json_encode($events, $jsonExportConsts);
echo "<script type=\"application/json\" id=\"eventList\">{$eventsJson}</script>"

PHP json to a JavaScript variable inside an HTML file

I write the following script that creates a nice JSON of all the images under the current folder:
<?php
header('Content-type: application/json');
$output = new stdClass();
$pattern="/^.*\.(jpg|jpeg|png|gif)$/i"; //valid image extensions
$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dirname) {
$files = glob(''.$dirname.'/*');
$images = preg_grep($pattern, $files);
$output->{$dirname} = $images;
}
echo json_encode($output, JSON_PRETTY_PRINT);
?>
I have an HTML file with a basic page and I want to display the JSON's data in a formatted way after some javascript manipulation.
So the question is how can I get the PHP data into a javascript variable?
<html>
...
<body>
<script src="images.php"></script>
<script type="text/javascript">
// Desired: Get access to JSON $output
</script>
...
<div>
<img ... >
</div>
</body>
</html>
I tried to put both https://stackoverflow.com/a/61212271/1692261
and https://stackoverflow.com/a/50801851/1692261 inside that script tag but none of them work so I am guessing I am missing something fundamental here (my ever first experience with PHP :)
you should focus on what needs to be done, but currently you are trying to implement your own idea. maybe you should change your approach and do what you want in another way?
passing php variable to js is possible. but for what reason do you need this json? if you want to operate with it to generate html (f.e show images to user) you can do it on pure php without js. if you need exactly json you can generate json file with php and and get this file via additional js request. but the simplest way is
// below php code that generates json with images
$images = json_encode($output, JSON_PRETTY_PRINT);
...
// php code but in html template
<script type="text/javascript">
var images = "<?= $images ?>";
</script>
I won't guarantee that this js line is going to work but you get the idea)
P.S you dont need to use stdClass for such purposes. we do it via arrays (in you case it will be associative arrays), arrays are very powerful in php. json_encode() will generate same json from both array or object. but if this part of code works fine that let it stay as it is
I took #Zeusarm advice and just used ajax (and jquery) instead.
For others need a reference:
Nothing to change in PHP script in the original post.
Add jquery to the HTML file with <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Make a GET request like this:
<script type="text/javascript">
var images = ''
$.get('images.php',function (jsondata) {
images = jsondata
});
I am sure this is not the cleanest code but it works :)

How to edit or replace xml string using php?

I had to change my question to simple question
For example: my XML file name is: ABC.xml
inside of this xml file is:
<li class="thumb"><a class="Alibaba" href="google.com"></a></li>
So, here is my question:
How to use PHP to search string inside of ABC.xml and find Alibaba name and replace it to AlibabaColor name and save it to ABC.xml
Please guide me and give me an example for this. Thank you
You can do this using php str_replace among many other functions. Here is a couple examples ->
If the XML is in a string already you can do this
PHP:
<?php
$myXmlString = str_replace('Alibaba', 'AlibabaColor', $myXmlString);
?>
If you need to get the XML data from another file there are a few ways to to do it depending on if you need to save it, just replace it and display it, or really what you are doing. Some of this comes down to preference.
Just need to display it?
<?php
$xml = file_get_contents(/path/to/file); // or http://path.to/file.xml
$myXmlString = str_replace('Alibaba', 'AlibabaColor', $xml);
?>
Need to change the file itself?
<?php
$xml = file_get_contents(/path/to/file); // or http://path.to/file.xml
$myXmlString = str_replace('Alibaba', 'AlibabaColor', $xml);
file_put_contents(/path/to/file, $myXmlString);
?>
--
To answer the below comment, here is working code from my server ->
xml:
<li>hello</li>
php:
$file = '/home/username/public_html/xml.xml';
$xml = file_get_contents($file);
$text = str_replace('hello','world',$xml);
file_put_contents($file, $text);
xml.xml after:
<li>world</li>
Keep in mind to change 'username' to the right one, or use an FQDN if you are more comfortable doing so. Make sure that the file has permission to be written to by a script as well.

Formatting datetime in JSON script

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.

How do I render javascript from another site, inside a PHP application?

What I'm trying to do is read a specific line from a webpage from inside of my PHP application. This is my experimental setup thus far:
<?php
$url = "http://www.some-web-site.com";
$file_contents = file_get_contents($url);
$findme = 'text to be found';
$pos = strpos($file_contents, $findme);
if ($pos == false) {
echo "The string '$findme' was not found in the string";
} else {
echo "The string '$findme' was found in the string";
echo " and exists at position $pos";
}
?>
The "if" statements contain echo operators for now, this will change to database operators later on, the current setup is to test functionality.
Basically the problem is, with using this method any java on the page is returned as script. What I need is the text that the script is supposed to render inside the browser. Is there any way to do this within PHP?
What I'm ultimately trying to achieve is updating stock from within an ecommerce site via reading the stock level from the site's supplier. The supplier does not use RSS feeds for this.
cURL does not have a javascript parser. as such, if the content you are trying to read is placed in the page via Javascript after initial page render, then it will not be accesible via cURL.
The result of the script is supposed executed and return back to your script.
PHP doesn't support any feature about web browser itself.
I suggest you try to learn about "web crawler" and "webbrowsers" which are included in .NET framework ( not PHP )
so that you can use the exec() command in php to call it.
try to find out the example code of web crawler and web browsers on codeproject.com
hope it works.
You can get the entire web page as a file like this:
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data('http://example.com/page.htm');
$my_file = 'file.htm';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $returned_content);
Then I suppose you can use a class such as explained in this link below as a guide to separate the javascript from the html (its in the head tags usually). for linked(imported) .js files you would have to repeat the function for those urls, and also for linked/imported css. You can also grab images if you need to save them as files.
http://www.digeratimarketing.co.uk/2008/12/16/curl-page-scraping-script/

Categories

Resources