-1

I have a php file with the following code:

echo($x);

Which simply prints

5.0 

How would I display this value in a html file?

8
  • What do you mean: "in a linked HTML file"? Commented Sep 24, 2015 at 3:59
  • I deleted the 'linked'. What I meant was that if I had both the php file and the html file on the same server, how would I get them to talk to each other. Commented Sep 24, 2015 at 4:00
  • You've already displayed it! haven't you?!! Commented Sep 24, 2015 at 4:00
  • Yes, but if I wish to create a html file to collect the output from multiple php scripts, so simply printing from a php file won't do. Commented Sep 24, 2015 at 4:03
  • So, you want to modify the contents of an existing HTML file using the output of a PHP script; don't you?! Commented Sep 24, 2015 at 4:03

1 Answer 1

2

You can use any HTML manipulation APIs, like DOMDocument class. But, just to get you started, I assume you have a very simple HTML file:

<html><head></head><body></body></html>

And you want to put the value of the $x variable inside the <body> tag using a <div> tag; simply:

<?php
$dom = new DOMDocument;
$HTML_file = "paht/to/your/file.html";
$dom->loadHTMLFile($HTML_file);

// To get the <body> tag in the HTML file
$xpath = new DOMXPath($dom);    
$body = $xpath->query('//body')->item(0);

// Insert some tags inside the <body> tag
$x = 5;
$element = $dom->createElement('div', $x);
$body->appendChild($element);

// overwrites to the same file
$dom->saveHTMLFile($HTML_file);
?>
Sign up to request clarification or add additional context in comments.

6 Comments

I am not sure if I am binding my html file properly as nothing shows up. Could you give me some tips on how to debug? Thanks so much in advance.
Also, should I change '//body' to something else?
@ttct Nothing is supposed to be showed, The script modifies the example HTML file; After the script execution, the sample file should be modified having a <div> inside the <body> tag which has the content of the $x variable. Also, the '//body' is just an XPath expression to select the <body> tag in the provided example; The code is just a simple example to get you started :)
Great, thanks a lot!
@ttct If it helps, please consider accepting it as an answer :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.