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.
Related
I have a flat file, TestFile.txt, that contains about 200 lines. Each item is a separate row. I show a partial of the contents of the TestFile.txt file below. I have PHP code working that reads TestFile.txt exactly as I need. The PHP read code searches the TestFile.txt, locates the line I wish to read, and places the result into an html input box. It parses the text after the = in the line, and only displays the data found after the =. Just as I need. Now I need to change the data in the html input box, and write the change back to TestFile.txt, and only update the text after the =. I show the PHP read code below. I have not a clue how to do what I need. I am a little over a week studying PHP. Any help with writing is much appreciated.
Thanks,
Mitch
Partial TestFile.txt:
RXFrequency=432675000
TXFrequency=432675000
RXOffset=260
TXOffset=120
Network=mnet.hopto.org
Password=9Yg81prqL0363zt
Latitude=34.657783
Longitude=-3.784595
Port=62021
Part of the PHP:
<!DOCTYPE html>
<html>
<body>
<?php
// Place text to look for in string $Search_String.
// The $Search_String will remain hard coded in my production
// code. The users will not be able to select $Search_String.
$Search_String_1 = "RXOff";
// Identify Text File, open File and Read the File.
$MyFile = fopen("TestFile.txt", "r") or die("Unable to open file!");
$found= "False";
// Create the while loop. Test each line with the if statement,
// looking for $Search_String, and place the result into string $line.
// Next, echo string $line which containes the found line in the
// flat text file. It will return the entire line even from a
// partial $Search_String, which is what I want.
/*...*/
// Next, let us build the array.
$lines = [];
while ( $line = fgets( $MyFile ) ) {
if ( str_contains( $line, $Search_String_1 ) ) {
//here you are keeping track of each line matching the criteria.
$lines[] = $line;
// This explode function will split the string contained
// in the $line variable at the =. Text left of the = is
// placed into the $key variable. Text right of the = is
// placed into the $value variable.
[$key, $value] = explode("=", "$line");
// echo $key; // RXOffset;
// echo $value; // 260;
//echo $line;
//echo $Search_String_1;
}
}
?>
<?php foreach($lines as $line): ?>
<?php endforeach;
// Properly close the text file.
fclose($MyFile);
// Get string $value from the explode code above.
?>
<label>RXOffset: <input type="text" id="message" value="<?php echo $value;?>"/></label>
<?php
</body>
<html>
Hope this gives enough information. Feel free to comment questions.
Thanks,
Mitch
This is what appears on the browser when I execute this PHP:
RXOffset: 269
Label Data
I just started to do some simple things with php. Now i have a question…Â
In this code i open a txt-file and write a key-value-array into it.
At the end I want to read out one value from this array which is stored serialized in the txt-document.
$open = fopen("write/doc.txt", 'w+');
$content = array ("red" => "FF0000", "green" => "#00FF00", "blue" => "#0000FF");
$contentserialized = serialize($content);
fwrite($open, $contentserialized);
fclose($open);
So until now all works properly. And with this code i can show the content of the file:
$file = file_get_contents("write/doc.txt");
echo $file;
But I want only one value out of it. How can I choose for example the value for key "green" on the page?
Would be nice if you can tell me!
echo unserialize($file)['green'];
or if that doesn't work(my php is a little rusty)
$array = unserialize($file);
echo $array['green'];
http://php.net/manual/en/function.unserialize.php
You could load the entire document and parse the content back into a PHP array. That would allow you to work with the data as any other arrays. Something like the following should be enough.
$file = 'write/doc.txt';
$fhandle = fopen($file, 'r');
$content = fread($fhandle, filesize($file));
$content = unserialize($content);
echo $content['green'];
Just as a good practice, remember to close the file handle.
fclose($fhandle);
Hope this helps.
http://php.net/manual/en/function.unserialize.php
<?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.
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++;
}
?>
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.