How to edit or replace xml string using php? - javascript

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.

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 :)

Download javascript output using file_get_content

Is it possible to download the resulting HTML code after the JavaScript code on the page has been run using PHP.
For example, when the page has this jQuery code $("p").html("Hello world"); and I use file_get_content('website.com') I don't get the string "Hello world" because the JavaScript runs after the page load.
use cURL:
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;
}
Then do :
<?php echo get_data('http://theURLhere.com'); ?>
Hope that helped
Please refer to similar questions and share your research you have done so far:
Get the content (text) of an URL after Javascript has run with PHP
Get Document source After AJAX or js Action With PHP
How to get content of a javascript/ajax -loaded div on a site?
Get HTML code after javascript execution using CURL PHP
One way to achieve this would be to use Selenium, and write a custom script to gather the output from it... But I'm sure that falls far beyond the scope of what you're attempting to do.
The way I would go would be to invert the responsibility. Have the JS send the output to a PHP endpoint, and use that output however you see fit.
Here's an example.
Javascript
<script>
var outputElement = 'html';
var HTML = $(outputElement).html();
var endpoint = 'myEndpoint.php';
$.post(endpoint, { html: HTML }, function(data) {
alert('Output sent');
});
</script>
One caveat here is that you will not get the DOCTYPE declaration, or any attributes on your HTML tag, if this isn't acceptable, you may reconstruct them in the PHP file below.
PHP
<?php
$html = $_POST['html']; // Be VERY CAREFUL with what you do with this...
// If you need to have the doctype and html tag... Use your own doctype.
// $html = sprintf('<DOCTYPE html><html class="my-class">%s</html>', $html);
// Do something with the HTML.
You have to be very careful when sending HTML over POST. If you're using this HTML to output on your website, it can easily be spoofed to reveal sensitive data on your website.
Reference
jQuery.post()

Get page contents after javascript prints

I am trying to get the contents of a page with file_get_contents but instead of getting the code for the javascript, is there a way to get what it prints?
<?php
$streams=file_get_contents("URL");
$myFile = "filename.txt";
$fh = fopen($myFile, 'w');
$stringData = $streams;
fwrite($fh, $stringData);
fclose($fh);
?>
I am told it is possible, the answers are already on Stackoverflow:
https://stackoverflow.com/a/2699303/2119863
http://php.net/manual/en/book.v8js.php
However, please think if it's a something you really must have. Since you want to get changed/dynamic results from a file, then include a 'script.js.php' file where the PHP will do the javascript work. JS is for user interaction, not server ;(

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