I'm generating your typical Web 2.0 HTML page with PHP: it contains a lot of <script>
tags and javascript code that will substantially change the DOM after the load event.
Is there a way to get the final HTML code directly from PHP, without opening the page with any browser?
For example, let's say the HTML for the page is (it's just an example):
<html>
<head>
<script>...the jquery library code...</script>
<script>$(document).ready(function() { $("body").append("<p>Hi!</p>");</script>
</head>
<body>
</body>
</html>
This HTML is saved in the $html
PHP variable. Now, I want to pass that variable to some function that will return $result = <html>....<body><p>Hi!</p></body></html>
.
Is this possible?
EDIT: since many of you were perplexed by my request I'll explain the reason. Unfortunately everything user facing was made in javascript and this makes the website uncrawlable by search engines. So I wanted to send them the post-ready event HTML code instead.
You can execute Javascript through PHP by calling javascript code/function as a string in PHP and send it to the client browser to execute.
echo '<script type="text/javascript">jsFunction();</script>';
To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.
PHP can run JavaScript directly with PHPv8. This is useful for running JavaScript both on the client and the server.
To evaluate JavaScript code using PHP, have a look at the V8 JavaScript engine extension, which you may compile into your PHP binary:
V8 is Google's open source JavaScript implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With