开发者

Imported file being added to the start of the page

开发者 https://www.devze.com 2023-04-10 05:32 出处:网络
I\'m using the following function to open a file: function example() { $foo = fopen(\'file.txt\', \'r\');

I'm using the following function to open a file:

    function example() {
$foo = fopen('file.txt', 'r');
while (!feof($foo)) {
    $foo2 = fgets($foo);
    echo $foo2;
}
}

H开发者_StackOverflow社区ere's the code where it's called:

<?php

include($_SERVER['DOCUMENT_ROOT']."/class_lib.php");

$page = new Page();

    function example() {
$foo = fopen('file.txt', 'r');
while (!feof($foo)) {
    $foo2 = fgets($foo);
    echo $foo2;
}
}

$page->meta = array
(
'title' => 'snip',
'description' => 'snip'
);

$page->content = "
snipsnipsnipsnipsnipsnip
<div id=\"foo\">
<pre>
".example()."
</pre>
</div>
<br/>snipsnip
";

$page->Display();

?>

For some reason, even though the function is called within the pre element, it appears at the start of the page (the file is output, then the html is loaded). Same thing happens when I use include(). I must overlooking something obvious... any ideas?

Here's the class_lib.php if it's needed: http://pastebin.com/7euqEWNq


You use echo when reading your file, so it's directly printed out.

You can used output buffering : ob_start

Or simply get the file content and use it instead or you function call : file_get_contents


What you should to is let the example method return a value as the result and than echo that at the position you are calling it from. Like so:

function example() { 
   $foo = fopen('file.txt', 'r'); 
   while (!feof($foo)) { 
     $foo2 = fgets($foo); 
     return $foo2; 
   } 
}

$exampleData = example();
$page->content = "snipsnipsnipsnipsnipsnip 
<div id=\"foo\"> 
   <pre>".$exampleData."</pre> 
</div> 
<br/>snipsnip"; 


I guess that's because your echo sentence, the first thing to be sent to the browser is the echo sentence output, so it shows first no matter where you place it.

You should return not echo, something like this:

function example() {
  $output = '';
  $foo = fopen('file.txt', 'r');
  while (!feof($foo)) {
    $foo2 = fgets($foo);
    $output .= $foo2;
  }
  return $output;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消