Meteoclimatic
Software => Tu Web meteorológica => Mensaje iniciado por: kocher en 26 de Febrero de 2022, 14:27:47
-
Buenos tardes a todos
Tengo un problema que sospechaba nimio o fácil de resolver; intento exponerlo:
Dispongo de un archivo PHP que obtiene unos determinados valores en un cierto orden:
12.6,11.1,02/26/2022 2:24 pm
Pues bien, me gustaría guardar exactamente esta línea de texto, en un archivo de texto; supongamos que en "test.txt"
Increíblemente, no he encontrado la solución je je
-
Hola kocher, muy buenas
La respuesta a tu pregunta es file_put_contents('nombrearchivoagrabar', 'contenido'):
https://www.php.net/manual/es/function.file-put-contents.php
tienes banderas como último argumento (sería el tercero) como FILE_APPEND para si quieres que agregue el contenido que le escribas o de lo contrario sobrescribirá lo que haya. Con eso puedes crear logs como por ejemplo el nombre del archivo con nombre del mes y/o día y líneas que se vayan agregando durante ese mes y/o día.
Ten en cuenta que lo hará cada vez que ejecutes el script.
Hay por ahí otro método más clásico y antiguo que comparte con otros lenguajes de programación (fopen, fread, fwrite, fclose), todo eso forma parte de las Funciones del Sistema de Archivos (https://www.php.net/manual/es/ref.filesystem.php) de PHP.
El método que yo he puesto es el más rápido.
Saludos desde Murcia ;)
-
Saludos jmviper
Nada, debo estar atontado o gafado
Explico un poco más y mejor; se trata de hacer, para un amigo, un archivo php que escribirá el resultado en un archivo de texto; así que tenemos lo siguiente:
- Archivo php: https://www.badameteo.com/fc-LogTemps.php (https://www.badameteo.com/fc-LogTemps.php)
- Archivo de texto para sobrescribirlo: https://www.badameteo.com/fc-temps.txt (https://www.badameteo.com/fc-temps.txt)
El archivo fc-LogTemps.php produce el resultado perfecto, pero ... aparecen °C caracteres no deseados en el archivo de texto fc-temps.txt
Una opción sería intentar eliminar esos caracteres, pero no lo consigo.
Otra opción, sería copiar literalmente el resultado del PHP al archivo de texto; hasta ahora no lo he sabido hacer
El archivo original php: https://www.badameteo.com/fc-LogTemps-original.php (https://www.badameteo.com/fc-LogTemps-original.php) contiene el siguiente código:
EDITADO POSTERIORMENTE
<?php
/*
fc-LogTemps.php
by Jim McMurry - jcweather.us - jmcmurry@mwt.net
04-04-09 - Changed the tag names and recommended times
01-11-15 - Updated the comments and changed the recommended tags. Also added the ?sce=view option to help me debug.
08-01-15 - Added filters to remove "units" if present and moved the self downloader code
*/
if ( isset($_REQUEST['sce']) && strtolower($_REQUEST['sce']) == 'view' ) {
//--self downloader --
$filenameReal = __FILE__;
$download_size = filesize($filenameReal);
header('Pragma: public');
header('Cache-Control: private');
header('Cache-Control: no-cache, must-revalidate');
header("Content-type: text/plain");
header("Accept-Ranges: bytes");
header("Content-Length: $download_size");
header('Connection: close');
readfile($filenameReal);
exit;
}
/*
Captures daily hi and nightly low temps for forecast comparisons. Captures $mintempovernight in the morning for use until the next reset. Same for the max temp in the evening.
This script should be run in the morning at a time that you think you've experienced the lowest overnight temperature depending on your climate and experience.
Then the same thing in the evening to capture the day's high. In both cases avoid the tag's reset time by going a few minutes early if necessary.
With these tags I run the script at 8:55 am and 8:55 pm. Feel free to use different tags if you wish.
- If the forecast you wish to compare is close to one of those times, delay the comparison until after the new temp is logged so you're logging good "actual" temps for that period.
- For any other comparisons that you might do, you've already got the best "actual" temp data for the previous day available.
For Weather Display
Requires that the following two lines be present in your testtags.txt file, or that the variables be populated another way.
They're different than in the readme file, but seem to work the best.
$maxtempoverday3 = %maxtempoverday3%; //maximum temperature 9am to 9pm
$mintempovernight = %mintempovernight%; //minimum temperature 9pm to 9am
Also requires that an empty text file named fc-temps.txt be placed in the same folder with this script and given write/read permissions
- If you stop using fc-LogTemps, then fc-temps.txt must be removed from your server so that the comparison script won't use that data.
*/
include("testtags.php"); // This if all files are in your root folder
//include("../testtags.php"); // Maybe something like this if you have the fc files in a special folder
//$maxtempoverday3 = str_replace("°F", "", $maxtempoverday3); // remove if "units" are turned on
$maxtempoverday3 = str_replace("°C", "", $maxtempoverday3);
//$mintempovernight = str_replace("°F", "", $mintempovernight);
$mintempovernight = str_replace("°C", "", $mintempovernight);
date_default_timezone_set("Europe/Madrid");
$log = "fc-temps.txt";
$now = date("G",time());
$lines = file($log); // Reads into an array
$entry = explode(",",$lines[0]); // to get the contents of the 1st (and only ) record
if ($now < 12) { // It's morning, so capture the nightly low
$entry[1] = $mintempovernight; // minimum temperature 9pm to 9am
} else { // It's evening, so capture the daily high
$entry[0] = $maxtempoverday3; // maximum temperature 9am to 9pm
}
$fp = fopen($log, "w") or die("Error: You must manually upload an empty text file named " . $log . " and give it write permissions (CHMOD 666).");
fwrite($fp, $entry[0] . "," . $entry[1] . "," . date("m/d/Y",time()) . " " . date("g:i a",time())); // Write the most recent entry
fclose($fp);
?>
Este código funciona perfectamente, pero aparecen los caracteres no deseados °C
Je je, ya se que soy un coñazo, pero es que me parece imposible no encontrar la solución
-
No eres ningún coñazo ni de coña *+* *+*
Viendo el código la respuesta es simple. Su funcionamiento es coger los datos del testtags.php generado por WD al que estas dos líneas:
$maxtempoverday3 = str_replace("°C", "", $maxtempoverday3);
$mintempovernight = str_replace("°C", "", $mintempovernight);
le quitan los susodichos ° a esas etiquetas de WD.
Luego por otra parte coge el contenido de ese archivo de texto fc-temps.txt y si la hora actual es menor a las 12 pone en ese archivo el valor de la mínima temperatura de la noche y si es sobre las doce pone la máxima del día.
El problema es que en ese archivo de texto está ya la de la mínima con el ° y no lo quita el script.
Así que tienes tres soluciones:
1- Editar el archivo de texto y quitar lo del °
2- Esperar a que sean más de las 0 h esta noche, se quitará porque ya pondrá el valor del testtags con eso quitado.
3- Cambias la siguiente línea:
$entry = explode(",",$lines[0]);
por esta otra:
$entry = explode(",",str_replace("°C","",$lines[0]));
eso quitará siempre ese molesto °
Y como ves al final el script hace un fopen, fwrite y fclose para escribir ese archivo.
Con cualquiera de los tres métodos irá bien, el 1 y el 3 serán inmediatos, el segundo habrá que esperar un poco todavía *-* *-*
Saludos kocher
-
je je je; eres un As jmviper
Has clavado el funcionamiento del script
He hecho lo que sugieres y parece funcionar bien todo; se puede ver llamando a la página:
https://www.badameteo.com/fc-LogTemps.php (https://www.badameteo.com/fc-LogTemps.php)
Produce el resultado deseado:
https://www.badameteo.com/fc-temps.txt (https://www.badameteo.com/fc-temps.txt)
No terminaba de entender la razón de que quitara un ° y dejara el otro; lo más curioso es que quitando el primero ya funcionaba el script para el que se han creado estos archivos:
http://badameteo.com/forecast-compare/test-fc.php (http://badameteo.com/forecast-compare/test-fc.php)
Muchísimas gracias por tu gran aportación
Muchísimas gracias de parte de mi amigo
Saludos desde San Sebastián
-
Muchísimas gracias por tu gran aportación
Muchísimas gracias de parte de mi amigo
De nada ;)
Saludos