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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行