Append html code to file using PHP - javascript

I have a Javascript function that takes a string and sends it via ajax to a PHP page. In PHP I would put this string inside the head tag (that already exist) of an html file. This change should be final. How could I do this? I don't know how to manipulate html code via PHP.

<?php
$htmlpage = file_get_contents('http://example.com/index.html');
echo str_replace("<head>", "<head>New text", $htmlpage);
//the result should be from <body></body> to <body>New Text</body>
?>
Also if you have text between body tags you can include it in
str_replace("<body>Old Text", "<body>New Text", $htmlpage)
If you have the string inside a varibale or you are using $_POST then instead of "<head>New text" put "<head>".$_POST['thestring']

Just use if/else statements and echo string from ajax to your tags if you can't use JS for this.

One way around this would be to use file_get_contents, then do a string replace on the tag with the amended code, and then write the changes with the ammended code.
Example
<?php
$file = "myhtmlfile.html";
$original = file_get_contents($file);
$needle = "<head>";
$new_content = "<head>\n".$_POST['header'];
$replacement = str_replace($needle, $new_content, $original);
file_put_contents($replacement, $file);
?>

Related

I want to display a php code shortcode in JavaScript, how do I do that?

This is my code
enter image description here
<script>
let myDiv = document.createElement("div");
myDiv.classList.add('test');
let my_var = `<?php echo do_shortcode("[elementor-template id="5078"]"); ?>`;
myDiv.innerHTML = my_var;
document.querySelector("#instagram").appendChild(myDiv);
</script>
Actually, it is not possible to do it this way because the script is being fired on the client-side while the PHP interpreter is working on the server-side.
If you are sure that you need to use JS to render some PHP code, I'd suggest sending a request using wp_ajax https://codex.wordpress.org/AJAX_in_Plugins to send a request on a server, and then the server can return any PHP code result that you want. Don't forget that shortcodes may use additional assets that will not be sent as a response.
The best way is to use shortcodes in a native form inside the content or PHP templates. Especially the elementor template where you can create template parts for different places of the website easily.
It's an enclosure problem:
You used nested double quotes in your php – resulting in breaking the echo.
Provided, your <script> tag is in your template php (so your php shortcode could be parsed) try this (replace the shortcode double quotes by single quotes):
<script>
let myDiv = document.createElement("div");
myDiv.classList.add('test');
let my_var = `<?php echo do_shortcode("[elementor-template id='5078']"); ?>`;
myDiv.innerHTML = my_var;
document.querySelector("#instagram").appendChild(myDiv);
</script>

how to convert this code to insert it in .js file

I'm trying to make my website multilingual, i have the php code also and i have translated files, but my site has also js file where is this words which i want to translate, there is example of this php code and how to insert it to js file?
There is JS code
// Update search list
rsParent.html($('<div>').attr({id: 'relatedSearches', class: 'contentBox'})
.append($('<div>').addClass('cbHead').text('Related Searches'))
.append($('<div>').addClass('cbBody').html(list)));
}
});
and the word "Related Searches" i want to replace with this php code
<?php echo $lang['CHARTS']; ?>
It is not possible to do it directly since PHP is a serverside language which is executed once on a webserver, unlike javascript that is executed in client's browser.
What you can do is encode your PHP array $lang to JSON and then output it as inline javascript and assign it to a variable in javascript.
<?php
echo "<script>";
echo "var lang = " . JSON_encode($lang) . ";";
echo "</script>";
?>
Make sure this php code is placed (executed) before your javascript file because variable lang has to be declared before your javascript is executed.

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.

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

Issues with PHP echo into a javascript

I am using the same line of code to echo a link onto my page in two locations and getting different results. One is inside an < a > tag and the other is inside a < script > tag. Below are the two excerpts of code (from the same tpl file) and the results:
<?php echo $btn['text']; ?>
Results in:
Filter
However in the script tag I have
url = "<?php echo $links['current_path']['href']; ?>"
And my result is
url = "index.php?route=module/jw/list&token=a4c693a4e38916fc03af23ad4fe1"
Notice the '&' after the route parameter. It is displaying the html code when I echo it inside the script tag. I know I can convert it in the second instance, but I am curious as to why I would need to. Why is the same php command making the symbol echo differently in various parts of the source code?
& is a HTML entity - your browser parses and displays it. Some similar questions about decoding here and here. Have you tried html_entity_decode():
html_entity_decode — Convert all HTML entities to their applicable characters
So
url = "<?php echo html_entity_decode($links['current_path']['href']); ?>"
Use the php function html_entity_decode
Example:
<?php echo $btn['text']; ?>

Categories

Resources