duanbiyi7319 2012-05-10 12:06 采纳率: 100%
浏览 23
已采纳

如何在PHP中提供动态HTML?

I've got a HTML file which I've created and is stored in a directory elsewhere.

The problem is, I'd like to be able to get content externally and place it within the HTML file.

I figured I could use PHP for this, because it's server-side and can access the files I want.

So, I created a PHP script which opens and echoes a HTML file, and afterwards, echos some JavaScript to change elements that are on the screen.

Here's my PHP file:

<?php

$html = file_get_contents('file.html');

$imageurl = file_get_contents('url.txt');

$js = '<script type=\'text/javascript\'>updateImage(\'img1\', '.$imageurl.');</script>';

echo $html;

echo $js;

?>

..and the HTML file:

<html>
<script type="text/javascript">
function updateImage(id, url) {
    var img = document.getElementsByName(id)[0];
    img.src = url;
}
</script>

<body>

<img src="" name="img1" />

</body>

</html>

It's not the best method, but it works.

I would like to know a way to do this within PHP, not using JavaScript.

I'm not sure as of the best approach to this.

  • 写回答

2条回答 默认 最新

  • doujiushi9007 2012-05-10 12:12
    关注

    You could use include and ob_get_contents to get the html as string and do some str_replace or preg_replace on that.

    Your HTML:

    <html>
        <body>
            <img src="{IMAGE_SRC}" width="512" height="512" name="image" />
        </body>
    </html>
    

    Your PHP:

    ob_start();
    include 'your_file.html';
    $buffer = ob_get_contents();
    ob_end_clean();
    $buffer = str_replace('{IMAGE_SRC}', 'your_image.png', $buffer);
    
    print $buffer;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?