file_get_contents returns PHP code

点点圈 提交于 2020-02-03 12:15:30

问题


When I use file_get_contents() function on a local file, the result contains php code, though I need HTML only.

Content of the file being read:

<?php echo '<p>Hello</p>';?>

And the result of file_get_contents called from a different file located in the same folder:

<?php echo file_get_contents('test.php'); //returns the following: string(31) "Hello'; ?>"

If I read a file from an external server, it returns HTML - as I would expect. So the question is: how do I get HTML output from the local file? Thank you all.


回答1:


You can use the files url (not filepath), so it is processed by the server eg:

echo file_get_contents('http://website.com/test.php');

However include/require would be better, eg:

include 'test.php';



回答2:


file_get_contents() only reads the plain file contents, as it's name suggests.

If you want the PHP interpreted, wou will have to include() it.

The according documentation can be found here: http://uk3.php.net/manual/en/function.include.php




回答3:


brainbowler alredy answered is pretty well. Additionally is suggest you to read the following docs:

  • http://de2.php.net/manual/de/function.include.php
  • http://de2.php.net/manual/de/function.require.php.

The PHP functions include and require are much alike and will do what you are trying to achive (they handle the include paths differently tough). There are also include_once and require_once which will also include and execute your script (and output the generated/contained HTML). But only once. They are useful if you haver your include statement in a loop or whatever and dont want it to load 42 times but only once.

Looks like you need to spend some more time on the basics (we all did). ;)



来源:https://stackoverflow.com/questions/24908777/file-get-contents-returns-php-code

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