2

File-1:

<?php
  <div>
    <p>
      something...
    </p>
   </div>
?>

File-2:

<?php
   $file1= What should I write to get output of File1?
?>

I need to get html output to the $file1 variable; Please help.

1
  • 3
    Your first file would not run for sure... Please clarify: is your File-1 a PHP file that you want to execute and grab its output, or is it an HTML file that you just want to read? Commented Nov 16, 2011 at 10:50

5 Answers 5

7

I think this will work for you:

function read($file) {
  ob_start();
  include($file);
  $content = ob_get_contents();
  ob_end_clean();

  return $content;
}

Use it like this:

$file = 'path/to/your/file.php';
$content = read($file);

To pass variables you can modify function above like this:

  function read($file, $vars) {
    ob_start();
    extract($vars, EXTR_SKIP);
    include($file);
    $content = ob_get_contents();
    ob_end_clean();

    return $content;
  }

  $file = 'path/to/your/file.php';
  $vars = array(
    'var1' => 'value',
  );
  $content = read($file, $vars);

You can access variables in included file like this: print $var1;

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

2 Comments

Thank you. It is working. If you would allow me I would add 1 question to you. If I want to send a variable to file-1 as like $_GET or $_POST then what should I do?
but what would be in file-1 to get vars? will it $getVer = $var1; or $getVar = $vars...
0

you can use

http://www.php.net/manual/en/function.ob-start.php

to start output buffering, then include your file and use

http://www.php.net/manual/en/function.ob-get-contents.php

to read what was the output and finish with

http://www.php.net/manual/en/function.ob-end-clean.php

to end the buffering.

Comments

0

Maybe is this you are looking for:

http://www.tizag.com/phpT/fileread.php

Visit the section: PHP - File Read: fread Function

Comments

0

You could either set the variable in File-1 and include it:

include() / include_once() / require() / require_once()

Or you could print the contents of File-1 and use output buffering:

http://www.php.net/manual/en/function.flush.php

Comments

0

Use this code:

   $content = file_get_contents('somefile.txt');

2 Comments

but he has php in that file, what he wants is the output of that file and not the file content itself.
he can call it through url e.g file_get_contents('localhost/file1.php'), in this way he can get the html content.

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.