How to operate txt file on PHP? - php

I have txt file, which keeps 1 as in the following query to take the contents from txt and +1
function analitic(){
$file = fopen(TEMPLATEPATH . "/analitic.txt", "w");
$txt = $_POST['data']; //$txt = 1
fwrite($file, $txt);
fclose($file);
}
And how to add a date in the txt file? And if the date is different, save the data in the next line?
Thank you google translate :)

This will work...
file_put_contents(TEMPLATEPATH."/analitic.txt",PHP_EOL.date('c').PHP_EOL,FILE_APPEND);
PHP_EOL - this the "next line" character
file_put_contents / FILE_APPEND is a slightly more concise method of writing to a file
'c' - is the date format for an ISO date time, please see http://php.net/manual/en/function.date.php for more information

Some think like this:
function my_action_myFunc(){
$data = $_POST['data'];
$date = date('d.m.Y');
$file = file_get_contents(TEMPLATEPATH."/analitic.txt",null,null, 10);
settype($file, "integer");
settype($data, "integer");
$a = $file+$data;
file_put_contents(TEMPLATEPATH."/analitic.txt",$date.PHP_EOL.$a);
wp_die();
}

Related

How to write the whole array of information into a file?

The script outputs a list and must write the entire list to a file. Why does the script write only the last line to the .txt file, and not the entire list? How do I fix a script to write the entire list to a .txt file?
$dir = "./radio/radio_stantion/";
$name = scandir($dir);
for($i=2; $i<=(sizeof($name)-1); $i++) {
$fopen=file( $dir.$name[$i] );
$line = $fopen[3];
$url = $fopen[2];
$radio_name = explode(") ", $line);
$radio_url = explode("//", $url);
$link = $radio_url[1];
$http = explode(":", $link);
$fff = $http[1];
$port = explode("/", $fff);
$zzz = $radio_name[1];
$finalname = preg_replace ("/[^a-zа-я\s]/si","",$zzz);
$sss = $finalname."-".$http[0]."-".$port[0];
--------------------------
A list is displayed:
FRESH FM IBADAN s4.voscast.com 8442
Bestfriend FM 178.32.62.172 8217
COOLfahrenheit 111.223.51.7 8005
RThess 37.59.32.115 6156
SmoothJazzcom 149.56.155.209 80
--------------------------
$f = fopen("../top_100/radio_top_100_v2.txt", "w");
fwrite($f, $sss);
fclose($f);
}
I barely understand whats going on there but the problem is that you are opening the file in write mode on each loop iteration.
Using fopen with w mode clears the file and writes to it:
'w' Open for writing only; place the file pointer at the beginning of
the file and truncate the file to zero length. If the file does not
exist, attempt to create it.
You should fopen the file before the loop. fwrite on each iteration. and fclose after the loop.
$f = fopen("../top_100/radio_top_100_v2.txt", "w");
for($i=2; $i<=(sizeof($name)-1); $i++) {
...
fwrite($f, $sss);
...
}
fclose($f);
I think you are overwriting the previous writes in every iteration. Try writing everything to a string variable first(and append a \n to each line), then write the string contents to the file one time. If you are dealing with a lot of data, then it would make sense to use fwrite every iteration, so not to consume too much memory.
File IO is expensive, so only opening the file once, and writing once, should improve performance as well.

Generate a TXT file from variables with a PHP file : can't add new lines?

I wrote a small code in PHP in order to parse variables.
I would like each time this code is called, a new line is added in the TXT file.
Each line will contain a time stamp , ie : 09:30 and a temperature value
Once the TXT file is filled-in i would like to generate a Google Chart.
Time Stamps are going to be Abcisses (X) and corresponding temp value will be Y
So far, a new line is NOT created in the TXT file.
Would you please help me to find out why ?
<?
$File = 'live_datas.txt';
# GRAB THE VARIABLES FROM THE URL
$HeuresTronconMesure = $_GET['hour'];
$MinutesTronconMesure = $_GET['min'];
$DonneeCapteur = $_GET['data'];
# --------------------------------
$FICHIER = fopen($File, "w");
# Generate Timestamp : HH:MM
fputs($FICHIER, $HeuresTronconMesure);
fputs($FICHIER , ":");
fputs($FICHIER, $MinutesTronconMesure);
# Add 1 space
fputs($FICHIER , " ");
# Add Temperature Value
fputs($FICHIER, $DonneeCapteur);
# Add a new line
fputs ($FICHIER , "\r\n");
# Close the file
fclose($FICHIER);
?>
At the end, i expect to get "live_datas.txt" with something like :
04:50 25.29
05:00 24.30
07:30 25.20
08:45 26.00
10:15 27.50
Regards,
You have to open your file in append mode:
$FICHIER = fopen($File, "a");
What manual says about both modes:
"w" (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist)
"a" (Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist)
//call function
writeData($_GET['hour'], $_GET['min'], $_GET['data']);
//function definition
function writeData($hour, $min, $temperature) {
$path = 'live_datas.txt';
$line = "{$hour}:{$min} {$temperature}\r\n";
if (file_exists($path)) {
file_put_contents($path, $line, FILE_APPEND);
}
else {
file_put_contents($path, $line);
}
}

PHP. Strange numbers in the end of JSON

I am reading and saving weather JSON data from forecast.io API. Because I am using free API which has 1000 requests limit per day. So I am requesting API every 10 minutes. I saving update time as timestamp and then I am using this timestamp to check to 10 minutes elapsed or not. However when I am reading JSON file and echoing it, strange number '18706' or '22659' coming out. I do not have idea where it is coming from. How to solve this problem?
Result in browser:
....madis-stations":["UTTT"],"units":"si"}}22659
PHP:
<?php
$t = time();
$last_updated_timestamp = file_get_contents("last_updated_timestamp.txt");
$delta = ($t - $last_updated_timestamp) / 60;
if ($delta > 10) {
$json = file_get_contents('https://api.forecast.io/forecast/MY_API_KEY/41.2667,69.2167?units=si&lang=ru');
$obj = json_decode($json);
echo $obj->access_token;
$fp = fopen('tw.json', 'w');
fwrite($fp, json_encode($obj));
fclose($fp);
$fp2 = fopen('last_updated_timestamp.txt', 'w');
fwrite($fp2, $t);
fclose($fp2);
}
echo readfile("tw.json");
?>
Change:
echo readfile("tw.json");
to just:
readfile("tw.json");
readfile writes the contents of the file to the output buffer, and then returns the number of bytes that it wrote. You're then echoing that number of bytes.
It seems like you confused readfile with file_get_contents, which returns the contents of the file as a string.
Remove the echo before readfile. Readfile already prints the content of the file. The return value of readfile is the number of read bytes, which you echoing.

Appending multiple entries to an output file with a crontab using php?

I am writing a script in PHP in which I had to write the system uptime, the current time, and the amount of users logged in the system into a log file, and be updated continually via a crontab.
What I need help with is that I would like the updates to accumulate within the file and be added continually. So far, whenever my script gets executed, the newest update overwrites the previous update.
What I've done is that I tried to declare an array of entries and as I iterate through the array push the contents of the update into the array (It might be a bit of half-baked logic on my part).
My Code:
$fileName = '../so-and-so directory/output.log';
$dt = date('m/d/y');
$time = date('h:i A');
$data = shell_exec('uptime');
$uptime= explode(' up ', $data);
$uptime = explode(', ', $uptime[1]);
$uptime = $uptime[0].','.$uptime[1];
$users = system('w', $who);
$array = new SplFixedArray(3);
$fileLog = fopen($fileName, 'w');
$fileString = "Date: ".$dt. "\n". " Time: ".$time . "\n".
"System uptime ". $uptime ."\n" ."Users " . $users;
foreach ($array as $entry) {
array_push(file_put_contents($fileName, $fileString));
}
fclose($fileLog);
I feel that the solution is very simple but I'm missing it. Would somebody please clue me in?
The "w" filemode truncates the file on open. "a" appends to the end instead. See fopen(3) or the PHP documentation for details.
Also, file_put_contents() is destroying the file. Try fwrite() instead.
drop fopen; simply use
file_put_contents($fileName, $fileString);
file_put_contents will overwrite the existing file by default.
In short:
$fileName = '../so-and-so directory/output.log';
$dt = date('m/d/y');
$time = date('h:i A');
$data = shell_exec('uptime');
$uptime= explode(' up ', $data);
$uptime = explode(', ', $uptime[1]);
$uptime = $uptime[0].','.$uptime[1];
$users = system('w', $who);
$fileString = "Date: ".$dt. "\n". " Time: ".$time . "\n".
"System uptime ". $uptime ."\n" ."Users " . $users;
file_put_contents($fileName, $fileString);
So it turns out that I needed to edit my crontab file as such:
* * * * * such-and-such-script.php >> ../so-and-so directory/output.log 2>&1
To make them append without the previous one being overwritten by the new one. I also lost the fopen() and instead of doing file_put_contents, I did fwrite() into the file. It works great now. Thank you!

PHP parsing/typecasting problems

What I'm trying to do is to convert some archived CSV data. It all worked well on a couple thousand files. I parse out a date and convert it to a timestamp. However on one file, somehow it doesn't work. I use (int) $string to cast the parsed strings to int values -> it returns int(0). I also used intval() -> same result. When I use var_dump($string), I get some weird output, for example string(9) "2008", which actually should be string(4) "2008". I tried to get to use preg_match on the string, without success. Is this an encoding problem?
Here is some code, it's just pretty standard stuff:
date_default_timezone_set('UTC');
$ms = 0;
function convert_csv($filename)
{
$target = "tmp.csv";
$fp = fopen("$filename","r") or die("Can't read the file!");
$fpo = fopen("$target","w") or die("Can't read the file!");
while($line = fgets($fp,1024))
{
$linearr = explode(",","$line");
$time = $linearr[2];
$bid = $linearr[3];
$ask = $linearr[4];
$time = explode(" ",$time);
$date = explode("-",$time[0]);
$year = (int) $date[0]);
$month = (int)$date[1];
$day = (int)$date[2];
$time = explode(":",$time[1]);
$hour = (int)$time[0];
$minute = (int)$time[1];
$second = (int)$time[2];
$time = mktime($hour,$minute,$second,$month,$day,$year);
if($ms >= 9)
{
$ms = 0;
}else
{
$ms ++;
}
$time = $time.'00'.$ms;
$newline = "$time,$ask,$bid,0,0\n";
fwrite($fpo,$newline);
}
fclose($fp);
fclose($fpo);
unlink($filename);
rename($target,$filename);
}
Here is a link to the file we are talking about:
http://ratedata.gaincapital.com/2008/04%20April/EUR_USD_Week1.zip
The file seems to be encoded in UTF-16, so it is indeed an encoding problem. The string(9) is caused by the null-bytes that you get if UTF-16 is interpreted as a single-byte encoding.
This makes the file hard to read with functions like fgets, since they are binary-safe and thus not encoding aware. You could read the entire file in memory and perform an encoding conversion, but this is horribly inefficient.
I'm not sure if it's possible to read the file properly as UTF-16 using native PHP functions. You might need to write or use an external library.
You may try to convert your file to plan ascii using iconv.
If you are on a linux or similar system that has iconv command:
$ iconv -f UTF16 -t ASCII EUR_USD_Week1.csv > clean.csv
Otherwise you may found the PHP iconv function useful:
http://php.net/manual/en/function.iconv.php

Categories