<?php
$myFile = "file.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
print_r ($theData);
fclose($fh)
?>
This is my current code, which has successfully read my file and printed the data to the screen. However now when I try to explode the data I just get a sever error and the page doesn't load at all, the only error message I get is page may be down for maintenance or configured incorrectly and I don't understand why it isn't working.
I am trying to put
$my_array = explode("/n", $theData);
after the data has been read, and before it is printed, but every time I add it the page gives up, but when I take it out the page loads again fine.
I need to be able to put in a foreach loop to explode the data and print it out one line at a time (it's an email directory) but I don't understand why it's not working.
$myFile = "file.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
$assoc_array = array()
$my_array = explode("\n", $theData);
foreach($my_array as $line)
{
$tmp = explode(" ", $line);
$assoc_array[$tmp[0]] = $tmp[1];
}
fclose($fh)
$mail = $assoc_array;
I have tried this code, which I found while doing the original research for how to read from .txt file to array, but it still throws up the server error problem.
Could someone explain where I'm going wrong?
In the end the code I've used is:
<?php
// Open the file
$filename = 'pvemail.txt';
$fp = fopen($filename, 'r');
// Add each line to an array
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
}
print_r ($array);
?>
I've managed to read the data and print each line out into an array, now all I need to do is make it look nice! Thanks a lot for your help guys!
Initial problems
Looks like you have a few missing semicolons, unless you typed the reference code by hand and your actual code is correct.
$assoc_array = array()
fclose($fh)
offset 1 does not exist
$tmp[1] does not exist, which means some $tmp either had no values or only one value. It is most likely the case that one of the lines is a single word without a space or completely empty.
Related
im searching for almost 2 hours for an solution for my problem.
i have a text file with a few lines:
Title1|||Content1
Title2|||Content2
Title3|||Content3
But now i want to change 2 specific line, for example Title2||Content2
i will send the id via url. so i know which line, but i wan't search via title or content which line php should change.
i have found this code:
$daten = file('../news.txt');
$fp = fopen('../news.txt', 'w');
foreach ($daten as $zeile){
$felder = explode('|||', $zeile);
if (!strcmp($felder[0], 'auto3')){
$felder[1] = 'xx';
$zeile = implode('-', $felder);
}
fwrite($fp, $zeile);
}
fclose($fp);
But how to change for expample
Title2|||Title3
of
$zeile[1]
which i get via
edit.php?id=1 ??
Sorry if I haven't understood your question correctly, don't kill me if my answer is wrong. In your case $daten is an array that contains the lines of the file "news.txt". $_GET['id'] will provide the offset that is required to edit the array.
$daten = file('../news.txt');
$fp = fopen('../news.txt', 'w');
$zeile = explode('|||', $daten[intval($_GET['id'])]);
$zeile[0] = 'ASD';//change Title1
$zeile[1] = 'FGH'."\r\n";//change Content1
$daten[intval($_GET['id'])] = implode('|||', $zeile);
fwrite($fp, implode('', $daten));
This question already has answers here:
Need to write at beginning of file with PHP
(10 answers)
Closed 9 years ago.
Hi I want to append a row at the beginning of the file using php.
Lets say for example the file is containing the following contnet:
Hello Stack Overflow, you are really helping me a lot.
And now i Want to add a row on top of the repvious one like this:
www.stackoverflow.com
Hello Stack Overflow, you are really helping me a lot.
This is the code that I am having at the moment in a script.
$fp = fopen($file, 'a+') or die("can't open file");
$theOldData = fread($fp, filesize($file));
fclose($fp);
$fp = fopen($file, 'w+') or die("can't open file");
$toBeWriteToFile = $insertNewRow.$theOldData;
fwrite($fp, $toBeWriteToFile);
fclose($fp);
I want some optimal solution for it, as I am using it in a php script. Here are some solutions i found on here:
Need to write at beginning of file with PHP
which says the following to append at the beginning:
<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
And other one here:
Using php, how to insert text without overwriting to the beginning of a text file
says the following:
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
So my final question is, which is the best method to use (I mean optimal) among all the above methods. Is there any better possibly than above?
Looking for your thoughts on this!!!.
function file_prepend ($string, $filename) {
$fileContent = file_get_contents ($filename);
file_put_contents ($filename, $string . "\n" . $fileContent);
}
usage :
file_prepend("couldn't connect to the database", 'database.logs');
My personal preference when writing to a file is to use file_put_contents
From the manual:
This function is identical to calling fopen(), fwrite() and fclose()
successively to write data to a file.
Because the function automatically handles those three functions for me I do not have to remember to close the resource after I'm done with it.
There is no really efficient way to write before the first line in a file. Both solutions mentioned in your questions create a new file from copying everything from the old one then write new data (and there is no much difference between the two methods).
If you are really after efficiency, ie avoiding the whole copy of the existing file, and you need to have the last inserted line being the first in the file, it all depends how you plan on using the file after it is created.
three files
Per you comment, you could create three files header, content and footer and output each of them in sequence ; that would avoid the copy even if header is created after content.
work reverse in one file
This method puts the file in memory (array).
Since you know you create the content before the header, always write lines in reverse order, footer, content, then header:
function write_reverse($lines, $file) { // $lines is an array
for($i=count($lines)-1 ; $i>=0 ; $i--) fwrite($file, $lines[$i]);
}
then you call write_reverse() first with footer, then content and finally header. Each time you want to add something at the beginning of the file, just write at the end...
Then to read the file for output
$lines = array();
while (($line = fgets($file)) !== false) $lines[] = $line;
// then print from last one
for ($i=count($lines)-1 ; $i>=0 ; $i--) echo $lines[$i];
Then there is another consideration: could you avoid using files at all - eg via PHP APC
You mean prepending. I suggest you read the line and replace it with next line without losing data.
<?php
$dataToBeAdded = "www.stackoverflow.com";
$file = "database.txt";
$handle = fopen($file, "r+");
$final_length = filesize($file) + strlen($dataToBeAdded );
$existingData = fread($handle, strlen($dataToBeAdded ));
rewind($handle);
$i = 1;
while (ftell($handle) < $final_length)
{
fwrite($handle, $dataToBeAdded );
$dataToBeAdded = $existingData ;
$existingData = fread($handle, strlen($dataToBeAdded ));
fseek($handle, $i * strlen($dataToBeAdded ));
$i++;
}
?>
My text file contains:
a
b
c
d
e
I can't figure out how to amend my code so that I can overwrite line 3 ONLY (ie replacing "c") with whatever I type into the input box 'data'. My code is as follows, currently the contents of the input box 'data' replaces my file entirely:
$data = $_POST['data'];
$file = "data.txt";
$fp = fopen($file, "w") or die("Couldn't open $file for writing");
fwrite($fp, $data) or die("Couldn't write values to file");
fclose($fp);
I have it working the other way around, ie the code below reads line 3 ONLY into the text box when the page first loads:
$file = "data.txt";
$lines = file( $file );
echo stripslashes($lines[2]);
Can anybody advise the code I need to use to achieve this?
The only way is to read the whole file, change the 3rd line, then write it all back out. Basically, like so:
$lines = file($file);
$lines[2] = $_POST['data'];
file_put_contents($file, implode("\n", $lines));
Btw, your reading code does not "ONLY" read line 3 - it reads all lines as per file() and then you only use line 3.
ok guys need your help again,
previously you all introduced me lightbox which after some tweaking has been great. except while using my php code there doesn't seem to be a way to add a caption to the image. now a friend of my introduced me to array using a .txt file. now this is all fine and dandy but i can't seem to get the code that we came up with to read the file correctly. currently it is randomly pulling the letter "a" and the letter "p" and assigning that, which i have no clue where it is getting this.
now here is the code that i've come up with to get the contents of the file.
<?php
// process caption file into named array
//open the file
$myFile = "captions.txt";
$fh = fopen($myFile, 'r') or die("Can't open file");
$theData = explode(fread($fh, filesize($myFile)),"\n");
//close the file
fclose($fh);
//parse line by line until there is no data left.
foreach ($theData as $item => $line) {
$exploded = explode("=", $line);
if (count($exploded) == 2) {
$myFile[$exploded[0]] = $exploded[1];
}
}
?>
and then i'm using the code that auto-populates my image album in turn activating the lighbtox.
<?php
$images = glob('*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach ($images as $image) {
if (file_exists("./thumbs/{$image}")){
echo "<img src=\"thumbs/{$image}\" alt=\"{$image}\" />";
}
}
?>
using this code generates no errors but doesn't properly read the captions file.
what i'm wanting to do is have the text file setup with the file name seperated by a = and then the caption.
here is a link to my test page if anyone wants to take a look.
http://outtamymindphoto.myftp.org/images/testalbum/testpage.php
You should start by fixing this line:
$theData = explode(fread($fh, filesize($myFile)),"\n");
According to the PHP Manual , the delimeter is the first parameter.
(array explode ( string $delimiter , string $string [, int $limit ] ))
(Read more about explode - http://php.net/manual/en/function.explode.php)
The right way:
$theData = explode("\n" , fread($fh, filesize($myFile)));
You'll also should try to output the variables in order to locate the problem.
For instance , use var_dump($var) to check $vars value.
Hope I helped you,
comment if you need further help.
I'm experimenting with fopen for the first time and was wondering if it was possible to search for a particular section within a file before adding or replacing that content with data?
Ideally, I'd like to:
Use fopen to get the file
Search for a comment called <!-- test -->
Replace that comment with new data.
This possible? (for the record - Appending data to the end of the file or adding new data to a specific line number would not work for what I'm working on as the file is constantly changing).
Thanks!
<?php
// make sure radio is set
if( isset($_POST['enableSocialIcons']) )
{
// Open file for read and string modification
$file = "/test";
$fh = fopen($file, 'r+');
$contents = fread($fh, filesize($file));
$new_contents = str_replace("hello world", "hello", $contents);
fclose($fh);
// Open file to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_contents);
fclose($fh);
}
?>
From: http://www.php.net/manual/en/function.fopen.php#81325
EDIT: To see what exactly is getting sent by your form do this at the top of the PHP file you're posting to:
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
exit;
?>
If you read the entire file in then use something str_replace to make the change, you should be able to get what you want.