Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute javascript in PHP

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.

like image 590
Thomas Bonini Avatar asked Apr 23 '10 14:04

Thomas Bonini


People also ask

Can you run JavaScript in PHP?

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.

How run js file in PHP?

echo '<script type="text/javascript">jsFunction();</script>';

How do you execute JavaScript?

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.

Can PHP and JavaScript interact?

PHP can run JavaScript directly with PHPv8. This is useful for running JavaScript both on the client and the server.


1 Answers

To evaluate JavaScript code using PHP, have a look at the V8 JavaScript engine extension, which you may compile into your PHP binary:

  • http://php.net/manual/en/book.v8js.php

V8 is Google's open source JavaScript implementation.

like image 108
SteAp Avatar answered Sep 16 '22 16:09

SteAp