duanshan1511 2015-12-08 14:03
浏览 46
已采纳

PHP是否写入文件

i tried to search, but still dont know the solution at all, for my next PHP code.

<?php
    $city="Budapest"; // Your city
    $country="hu"; // Two digit country code
    $url="http://api.openweathermap.org/data/2.5/weather?q=".$city.",".$country."&appid=2de143494c0b295cca9337e1e96b00e0&units=metric";
    $json=file_get_contents($url);
    $data=json_decode($json,true);
    $file = '/home/cs2d/sys/lua/weather.dat';
    $current = file_get_contents($file);
    $current .= $data['weather'][0]['main']."
".$data['main']['temp']."
";
    // Write the contents back to the file
    file_put_contents($file, $current);
?>

As you can see it's a simple code, which write values into the weather.dat file. But how to possible to do that its just refresh lines instead of add new one.

Any idea?

  • 写回答

1条回答 默认 最新

  • dsfs64664 2015-12-08 14:14
    关注

    This works :

    $city="Budapest"; // Your city
    $country="hu"; // Two digit country code
    $url="http://api.openweathermap.org/data/2.5/weather?q=".$city.",".$country."&appid=2de143494c0b295cca9337e1e96b00e0&units=metric";
    $json=file_get_contents($url);
    $data=json_decode($json,true);
    $file = 'weather.dat';
    
    $current = file_get_contents($file);
    $contents = file_get_contents($file);
    echo $current;
    $contents = str_replace($current, ' ', $contents);
    echo $contents;
    
    file_put_contents($file,$contents);
    $current = file_get_contents($file);
    $current .= $data['weather'][0]['main']."
    ".$data['main']['temp']."
    ";
    // Write the contents back to the file
    file_put_contents($file, $current);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料