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']."\n".$data['main']['temp']."\n";
// 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?
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']."\n".$data['main']['temp']."\n";
// Write the contents back to the file
file_put_contents($file, $current);
Related
Here is the script normally. It saves data to a file.
<?php
if (isset($_GET['field'])) {
$file = 'data.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= "\n".$_GET['field'];
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
But I want it to add (added by a user) at the end of what is sent. I have tried this:
<?php
if (isset($_GET['field'])) {
$file = 'data.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new line to the file
$current .= "\n".$_GET['field'] + "(added by a user)";
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
But it doesn't work. How do I do this?
So, I have a code that based on user's input write data to the file. Basically user select the date and the workout which on submit get written to the file. When I try to set it up to check if the string (date) already exist in the file I cannot make it work so that existing line is replaced.
Current code that is writing user's input to the file:
<?php
include 'index.php';
$pickdate = $_POST['date'];
$workout = $_POST['workout'];
$date = ' \''.$pickdate .'\' : \'<span>'.basename($workout,'.txt').'</span>\',' .PHP_EOL;
$file = 'test.js';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new workout to the file
$current .= $date;
$current = preg_replace('/};/', "", $current);
$current = $current.'};';
// Write the contents back to the file
file_put_contents($file, $current);
header("location:index.php");
?>
My attempts were with if statement but again I couldn't manage to write the code that will replace the line with if exists. This is what I have:
<?php
include 'index.php';
$pickdate = $_POST['date'];
$workout = $_POST['workout'];
$date = ' \''.$pickdate .'\' : \'<span>'.basename($workout,'.txt').'</span>\',' .PHP_EOL;
$file = 'test.js';
// Open the file to get existing content
$current = file_get_contents($file);
if (strpos($current, ' \''.$pickdate .'\'') ) {
#here is where I struggle#
}
else {
// Append a new workout to the file
$current .= $date;
$current = preg_replace('/};/', "", $current);
$current = $current.'};';
// Write the contents back to the file
file_put_contents($file, $current);
}
header("location:index.php");
?>
Currently it is doing this
08-04-2014 : Chest
08-05-2014 : Legs
08-04-2014 : Back
I want this
Now when user choose August 4th again that line to be replaced with new/same choice of workout depending what user selects.
08-04-2014 : Back
08-05-2014 : Legs
Can someone help with the part where I struggle to make this work. Thank you so much in advance.
As explained by Barmar in the comments:
$current = trim(file_get_contents($file));
$current_lines = explode(PHP_EOL, $current);
/* saved already */
$saved = false;
foreach($current_lines as $line_num => $line) {
/* either regex or explode, we explode easier on the brain xD */
list($date_line, $workout_line) = explode(' : ', $line);
echo "$date_line -> $workout_line \n";
if($date == $date_line) {
/* rewrite */
$current_lines[$line_num] = "$date : $workout";
$saved = true;
/* end loop */
break;
}
}
/* append to the end */
if(!$saved) {
$current_lines[] = "$date : $workout";
}
file_put_contents($file, implode(PHP_EOL, $current_lines));
So, you explode the file, go thru it, line by line, if found overwrite that line, if not append it to the end of the array, then glue it back together and put it back in the file.
You'll get the idea.
Hope it helps.
I'm trying to edit a file by line using SplFileObject(). I can choose the line of the file I want to edit. But how do I then write a $string to that line?
Here is my code to get the line:
<?php
$file = new SplFileObject('myfile.txt');
$file->seek(9999); // Seek to line no. 10,000
echo $file->current(); // Print contents of that line
?>
How do I insert a string on that line?
Note, I don't want to overwrite the file, I simply want to insert a $string at a given line.
This isn't probably the best solution as it will read the whole file and store it in a string. But since there are no other answers you can use this as your last resource.
$ouput = '';
$file = new SplFileObject("your_file.xxx", 'r');
while (!$file->eof()) {
$line = $file->fgets();
if($line == 'your_condition'){
$line = 'replace this line';
}
$output .= $line;
}
$file = null;
$file = new SplFileObject("your_file.xxx", 'w+');
$file->fwrite($output);
Imagine I have a TXT file with the following contents:
Hello
How are you
Paris
London
And I want to write beneath Paris, so Paris has the index of 2, and I want to write in 3.
Currently, I have this:
$fileName = 'file.txt';
$lineNumber = 3;
$changeTo = "the changed line\n";
$contents = file($fileName);
$contents[$lineNumber] = $changeTo;
file_put_contents($fileName, implode('',$contents));
But it only modifies the specific line. And I don't want to modify, I want to write a new line and let the others stay where they are.
How can I do this?
Edit: Solved. In a very easy way:
$contents = file($filename);
$contents[2] = $contents[2] . "\n"; // Gives a new line
file_put_contents($filename, implode('',$contents));
$contents = file($filename);
$contents[3] = "Nooooooo!\n";
file_put_contents($filename, implode('',$contents));
You need to parse the contents of the file, place the contents in a new array and when the line number you want comes up, insert the new content into that array. And then save the new contents to a file. Adjusted code below:
$fileName = 'file.txt';
$lineNumber = 3;
$changeTo = "the changed line\n";
$contents = file($fileName);
$new_contents = array();
foreach ($contents as $key => $value) {
$new_contents[] = $value;
if ($key == $lineNumber) {
$new_contents[] = $changeTo;
}
}
file_put_contents($fileName, implode('',$new_contents));
I have a simple file.txt which needs to be over written every time I run a certain php code.
$msg ="string";
$file = 'file.txt';
$opn = file_get_contents($file);
$opn .= $msg;
file_put_contents($file, $opn);
The code works perfectly, It added the string I want it to add, but It is appending it to the former. I want it to erase it blank and then write.
I've read the manual http://php.net/manual/en/function.file-put-contents.php
I am not using the FILE_APPEND argument either.
It's a simple thing that I'm not seeing. Help me out.
EDIT:
Here is the whole code. I'm getting some data from a site. The data is in this format 12.222 AAA and I am trying to save that to a text file to easily access later.
But for some reason something does not work. The scraper works perfectly, and the file_put_contents() woks perfectly if I set the $item="string"; but it does not work when when $item is set to equal the code below. If I echo $item I get what I want.
<?php
include('simple_html_dom.php');
$html = file_get_html('http://site.com/boom');
// find the thing in the span
foreach($html->find('div') as $article) {
$item = $article->find('span', 0)->plaintext;
echo $item;
$file = 'file.txt';
$fh = fopen( 'file.txt', 'w' );
fclose($fh);
$opn = file_get_contents($file);
$opn .= $item;
file_put_contents($file, $opn);
}
?>
you are concatenating the string in $opn .= $msg;
You can use
$msg ="string";
$file = 'file.txt';
file_put_contents($file, $msg);
No need to read the data.
You're reading the contents of the file into a string variable ($opn), appending your message ($msg) to $opn, then writing $opn back to file.... the append you're doing is
$opn .= $msg;
If you want to write only $msg to the file, then use
file_put_contents($file, $msg);
<?php
$msg ="string";
$file = 'file.txt';
$fh = fopen( 'file.txt', 'w' );
fclose($fh);
$opn = file_get_contents($file);
$opn .= $msg;
file_put_contents($file, $opn);
?>
This code will do what you are looking for..:)
file_put_contents($file, $opn,FILE_APPEND);