6

readfile() says it outputs the content but I want the content to be saved in a variable. How do I do that? I tried $content=readfile("file.txt") but that doesn't come out right.

I want to do like this:

$data=readfile("text.txt");
echo htmlentities($data);

That should give you an idea of how I want that to work.

2
  • one more thing, I do know about file_get_content()... but I am stumped about that particular "readfile()"... wondering how do I assign a variable to the buffer? Commented Jun 7, 2012 at 19:49
  • If you already know than why not use it. readfile and file_get_contents are for doing two different things and what you want to do is exactly what file_get_contents is for, not what readfile is for. Commented Jun 7, 2012 at 19:51

2 Answers 2

20

That is what file_get_contents is for:

$data = file_get_contents("text.txt");
echo htmlentities($data);

If you must use readfile you can use output buffering to get the contents into a variable:

ob_start();
readfile("text.txt");
$data = ob_get_clean();
echo htmlentities($data);

I don't see why you would avoid file_get_contents in this situation though.

Sign up to request clarification or add additional context in comments.

4 Comments

that's the answer I am looking for. It's not gonna be used, really but I was curious where the buffer is when I do the "readfile()" - the doc said it outputs to a buffer so I figured why not assign a variable to that buffer but when I did that, it failed to do what I expected - well it output but ended with a number. It's more of a programming concept that I needed to grasp when dealing with a buffer.
Ah, I see. I will leave in the bit about file_get_contents so that anyone who comes across this knows that is what they should use. And for your knowledge, everything in PHP is written to a buffer by default called the output buffer. statements like echo "Test"; write to that buffer as well. That buffer is flushed to actual output depending on different settings. It could be flushed every 4KB of data, or not until the end of the script for example.
ob_start just captures the output buffer, allowing you do extra processing to it if you want to or prevent it from outputting at all. It's useful if you want to call a function from some library and that function uses echo to output stuff, but you don't want it to output anything, or you want to process its output before outputting it.
amazing how it suddenly makes sense now that I know what buffer, obstart(), and ob_get_clean() are all about - it just doesn't hit me until just now.
0

readfile() writes the contents of the file to a buffer. Use file_get_contents() instead.

Comments

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.