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.