1

I'm trying to define a string as a combination of hard coded characters and of the contents of another file. What I have tried is this.

$html = "<h1>
           ".file_get_contents("file.php", TRUE)."
        <h1>";

The problem is that only raw text is being returned from file.php. Whatever it is that PHP is supposed to echo isn't being echoed..

3 Answers 3

1

You need output buffering to do that:

function generate_h1()
{
    ob_start();
    include('file.php');

    return '<h1>' . ob_get_clean() . '</h1>';
}

$html = generate_h1();

See also: ob_start() ob_get_clean()

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

2 Comments

Is there any way that I could put parameters on the URL? I don't think it's possible to pass variables along the URL path with require() or include(), is it?
@Lance if you're passing a URL to include(), you can pass parameters. I would advice against include() from remote location though.
0

You need to use include or require instead of file_get_contents. file_get_contents won't execute a local file, it just gets its contents - the plain-text PHP code.

2 Comments

Well, $html = "<h1>".require("file.php")."</h1>"; wont work though. Is there something with a buffer that I need to do?
Yes, @Jack's answer gives you info on doing that.
0

file_get_contents() returns the actual source of a file and it does not use it as a script. What you need is either

include 'file.php'; //or
require 'file.php';

or better yet

include_once 'file.php';
require_once 'file.php';

This is better in case you have functions declared in file.php. If you include a file twice it will throw an error saying that a function has been declared more than once. so include_once if it's something that you can live without in case something happens to the file or require_once which will result a fatal error if the file does not exist.

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.