PHP是否写入文件

时间:2015-12-08 14:03:57

标签: php

我试图搜索,但仍然根本不知道解决方案,我的下一个PHP代码。

<?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']."\n".$data['main']['temp']."\n";
    // Write the contents back to the file
    file_put_contents($file, $current);
?>

正如您所看到的,它是一个简单的代码,它将值写入weather.dat文件。 但是如何做到这一点只是刷新线而不是添加新线。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这有效:

$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']."\n".$data['main']['temp']."\n";
// Write the contents back to the file
file_put_contents($file, $current);