解析xml并在php中正确使用fwrite

My problem here is that i don't know how to properly write a file using fwrite. I parse xml using simplexml and then, while echo works fine, i can't write the same result in a file. In this example below, i echo 5 items from an xml feed, but when i write it to a file, it writes the 5th item only. Can anyone tell what's the problem?

$file = simplexml_load_file($url); {
$c = 0;
foreach($file->channel->item as $post) {
if($c == 5){
break;
}

$headline = (string) $post->title;

echo $headline;

$fp=fopen('myfile.htm', "w+");  
fwrite($fp, $headline."<br />");
fclose($fp);
        $c++;
        }
}

EDIT : Second attempt . I used a while loop, instead of if, but i only managed to write 5 times the 5th item. I need w+ (and not a+) to overwrite file every time it is updated and not add content each time:

$file = simplexml_load_file($url); {

foreach($file->channel->item as $post) {

$fp=fopen('myfile.htm', "w+");
$c = 1;
while ($c <= 5){
    $headline = (string) $post->title;
    fwrite($fp, "$headline<br />");
    $c++;
}
fclose($fp);
}
include 'myfile.htm';
}

You can either open the file outside the loop, or if you must open it inside, open it with a mode.

$fp = fopen('myfile.htm', 'w+');
foreach(...) {
    //write here
}  
fclose($fp);

or

foreach(...) {
    $fp = fopen('myfile.htm', 'a');
    //write here
    fclose($fp);
}

What the w+ mode does is open the file in write mode, and points to the beginning of the file, which results in only the last iteration being written in the file. All the previous iterations are overwritten.

You need to open the file for appending:

change:

$fp=fopen('myfile.htm', "w+");  

to:

$fp=fopen('myfile.htm', "a");  

And, you should open the file before you start the loop for efficiency and close it after the loop.

the "w+" in your fopen opens the file "for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it."

Whenever you open a file with the w+ command, it will start writing at the beginning of the file and delete any data already in the file. If you still want to use the "w+", you ought to place the fopen command before the loop (and also the fclose after the loop) to write the way you want.

see: http://www.php.net/manual/en/function.fopen.php

Instead of opening the file in 'w+' mode you need to use 'a' mode and you should open the file before the loop as it is the same file you are opening each time and close the file after the loop.

$fp=fopen('myfile.htm', "a+");  

//the loop starts here

//your code

// the loop ends here.

fclose($fp);