在另一个html文件中显示php echo

时间:2015-09-24 03:52:18

标签: php html

我有一个包含以下代码的php文件:

echo($x);

简单打印

5.0 

如何在html文件中显示此值?

1 个答案:

答案 0 :(得分:2)

您可以使用任何HTML操作API,例如DOMDocument类。但是,为了让您入门,我假设您有一个非常简单的HTML文件:

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

并且您希望使用$x标记将<body>变量的值放在<div>标记内;简单地:

<?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);
?>