6

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.

3 Answers 3

4

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';
Sign up to request clarification or add additional context in comments.

Comments

4

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: https://www.php.net/manual/en/function.include.php

Comments

0

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

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

1 Comment

Thank you for the explanation, I completely agree on the need to spend more time learning the language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.