duanbigan7765 2013-02-09 00:09
浏览 59
已采纳

解析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';
}
  • 写回答

3条回答 默认 最新

  • dsgixl5195 2013-02-09 00:16
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000