简体   繁体   English

PHP包含之前修改文件的内容

[英]PHP Modify content of file before is included

Is possible to somehow modify the content of file that is being included in the existing code by require function? 是否可以通过require函数修改包含在现有代码中的文件内容? For example I am including file in my code like this: 例如,我将文件包含在我的代码中,如下所示:

require $page_body;

Now I want to omit the HTML tags using the strip_tags function to get rid of HTML tags. 现在,我想使用strip_tags函数省略HTML标签,以摆脱HTML标签。 If this code contains pure HTML tags without PHP code ( <?php /* php code goes here */ ?> ) the following works as expected: 如果此代码包含不带PHP代码的纯HTML标记( <?php /* php code goes here */ ?> ),则可以正常工作:

  $content =  strip_tags(file_get_contents($page_body));
  echo $content;

But if my $page_body is mixture of HTML and PHP the echo returns nothing, when I've printed $content using print_r it seems like several empty strings 但是,如果我的$page_body是HTML和PHP的混合体,则回声不返回任何内容,当我使用print_r打印$content ,似乎有几个空字符串

[wakatana@HP-PC v2]$ php includer.php 













[wakatana@HP-PC v2]$ 

My guess is that strip_tags did not works well with HTML code where alos PHP is included. 我的猜测是, strip_tags不适用于包含alos PHP的HTML代码。

When you use require or include, the code is inserted inside the file, after that you cant change it. 当您使用require或include时,代码将插入文件中,之后您将无法对其进行更改。

What you can do is open the file with fopen() and then do all the changes and save the file. 您可以使用fopen()打开文件,然后进行所有更改并保存文件。 After all that, when you load the file again it will be as you wanted it to. 毕竟,当您再次加载文件时,它将如您所愿。

If you don't want to change the actual file, you can open the original, as well as a temporary file, copy information from original, change it, save it to temporary file, include the temporary file and then delete it. 如果您不想更改实际文件,则可以打开原始文件以及临时文件,从原始文件中复制信息,进行更改,将其保存到临时文件中,包括该临时文件,然后将其删除。 This way you will have the original information changed the way you like without changing the original file. 这样,您将以自己喜欢的方式更改原始信息,而无需更改原始文件。

One solution could be output buffering , I suggest you check it out, can be useful for other stuff too. 一种解决方案可能是输出缓冲 ,我建议您检查一下,这对其他内容也可能有用。

ob_start();
require $page_body;
$content = ob_get_clean();
echo strip_tags($content);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM