How to include a php file in a html file via a php script [duplicate]

旧巷老猫 提交于 2019-12-13 22:26:09

问题


I already post this question before but people always ask unnecessary question. I'm gonna explain it in a simple way.

I HAVE 3 files :

  1. a php file (contains only html, thats important) : We call it X file for the example.
  2. a php file where there's some database query to insert database data on the screen : Y file
  3. a php file (a script that will make some manipulations) : Z file

SO, i want to include Y into X with the script of Z.

In Z, i make a str_replace($text, $new, file_get_contents($file));

The ONLY THING is that i need to include PHP open and close TAGS in X because there's no php tags in it.

So, $new = "<?php include('Y.php'); ?>";. If you try, the close tag wont be considered in the string, but that's what i want.

Hope this question is NOW clear. I can't be more clearer than that. :D

Thanks for you advice.


回答1:


To include a file you do

<?php
include(file);
?>

So in this case

X contains <?php include('Y'); ?> And Y contains <?php include('Z') ?>

But if you are doing what i think you are doing (a template of some sort) you would be better of by looking into overflow buffer ( ob_start and ob_end_flush for example )

Those can place all echoed information into a variable to be modified later, also the php inside is run, instead of just read as text as in your example with the file_get_contents()




回答2:


The question is very unclear and vague, but I have a guess:

File X is some HTML where you want to replace special markers.
File Y loads the value from DB that should replace the marker.
File Z does the replacement.

This could be solved like that (File Z):

<?php
ob_start();
include("Y.php");
$repl = ob_get_contents();
ob_end_clean();

ob_start();
include("X.php");
$src = ob_get_contents();
ob_end_clean();

echo str_replace("THEREPLACEMENTMARKER", $repl, $src);
?>


来源:https://stackoverflow.com/questions/14986890/how-to-include-a-php-file-in-a-html-file-via-a-php-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!