user000000
user000000

Reputation: 75

Get result of HTML and JavaScript code in PHP

I want to get the result of shown JavaScript and HTML code. For example, when we write document.write("Hello"), return "Hello". Look at this code:

$html_code = <<<EOL

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>Hello World</title>
        </head>
        <body>
            <script>
                document.write("Hello World");
            </script>
        </body>
    </html>

EOL;

$result = getResult($html_code);

echo $result;

I want to get this result:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Hello World</title>
    </head>
    <body>
        Hello World
    </body>
</html>

Upvotes: 1

Views: 304

Answers (1)

hherger
hherger

Reputation: 1680

I understand that you want to get the result of a HTML page with embedded Javascript code on the server side, in the same script that generates this HTML and Javascript code.

You can not!

The reason

  • The PHP script runs on the server side.
  • The HTML code (with the embedded Javascript code) has to be interpreted by a browser on the client side.
  • The browser would execute the Javascript code. And only then the Javascript code (document.write("Hello World");) would create the "Hello world" HTML text. And only then the HTML text would look like you are expecting.

In brief: you expect a result on the server side which had to be produced on the client side before.

In your example you could directly have the PHP script generate the "Hello world" text - no need for Javascript.

Upvotes: 1

Related Questions