Write to file using SplFileObject() - php

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);

Related

How can I delete lines that I read from file line by line in PHP

I have a code here:
$file = fopen('a.txt', 'r');
while (!feof($file)){
$word = trim(fgets($file));
// calling a function on $word
}
I want to delete the $word at the end of while. How can I do this?

Can I add an image path from a .txt file in a webpage using PHP?

I need to dynamically add in the img src full file path to a file from a .txt file. So far i have been using the below code to populate titles, and descriptions:
< ?php
$myFile = "film_music/feature1.txt";
$lines = file($myFile);//file in to an array<br />
echo $lines[0]; //line 1
? >
The feature file contains all details for movies that will eventually be displayed here:
http://www.londonosophy.com/film_music2.php
Currently the file contains the following rows:
Sightseers (2012)
Dark comedy, featuring Alice Lowe
images/Sightseers-TinaPencil.jpg
Does anyone know php code that can read line X (or line 3 in this case) and dynamically populate the img src="" file path?
Many thanks in advance for your suggestions!
If you need to iterate over lines and need to check if line contains file path (for example, if sometimes there are white lines between blocks and sometimes they are missing), then:
<?php
$myFile = 'film_music/feature1.txt';
$lines = file($myFile);
$needle = 'images/';
$needleLen = strlen($needle);
foreach ($lines AS $line) {
$line = trim($line);
if (substr($line, 0, $needleLen) == $needle) {
echo '<img src="' . $line . '" alt="" />';
}
}
?>
You need to fetch 3rd line of the file every time, because it contains that path of the image.
<?php
global var $raw;
$myFile = "film_music/feature1.txt";
// open file...
$lines = file($myFile);//file in to an array<br />
for($i=2;$i<=no_of_lines;$i+3){
$raw = $lines[$i];
}
// Populate $raw variable where you need.
?>
Use $fh = fopen(...) and loop every line.
while (!feof($fh)) {
$line = fgets($fh);
if ($line === false) {
throw new Exception("File read error");
}
[do your things.]
}
http://www.php.net/manual/en/function.fopen.php
You can read each line of text line as:
$lines=file('file.txt');
$lines=array();
$fp=fopen('file.txt', 'r');
while (!feof($fp))
{
$line=fgets($fp);
//process line however you like
$line=trim($line);
//add to array
$lines[]=$line;
}
fclose($fp);
if you don't need any special processing, this should do what you're looking for
$lines = file($lines, FILE_IGNORE_NEW_LINES);
may this help you... :)
you can check all line of text file with in_array("you want", $lines) as you desire...if its not dynamically....

Get only one line from a web page

Hi, I have this file test1.php and in the other file test.php I have this
php code running:
<?php
$file = "http://inviatapenet.gethost.ro/sop/test1.php";
$line = '0';
if($f = fopen($file, 'r')){
$line = fgets($f); // read until first newline
fclose($f);
}
echo $line;
?>
The idea is to get just the second line of the web page test1.php.
Second Line
I've tried to change the $line = '2'; but no affect, it just displays the first line.
I need Help.
You can use file which reads a file into an array, you can then grab whichever line you want by using the index you want.
For example:
data.txt:
line one
line two
line three
line four
PHP code:
$file = file('data.txt');
echo $file[1]; // echo line number 2, remember arrays start at 0!
Updated PHP code for new versions (5.4):
echo file('data.txt')[1];
This should work. Obviously, change only the value of $linetofetch:
<?php
// Write here the number of the line you want to fetch.
$linetofetch = 2;
$file = "http://inviatapenet.gethost.ro/sop/test1.php";
$currentline = 1;
if($f = fopen($file, 'r')){
while ($currentline <= $linetofetch) {
$line = fgets($f); // read until first newline
$currentline++;
}
fclose($f);
}
echo $line;
?>

write the out put on file

I am very new to php, and i have search and put together this script to convert text to csv and write the out put on the file.
$File = "/var/apache2/htdocs/loginS/host.txt";
$Handle = fopen($File,"r");
$Content = fread ($Handle,filesize ($File));
fclose($File);
fclose($Handle);
$Content = explode("\t", $Content);
foreach($Content as $Value) {
//echo $Value."|"; // till this line working
fwrite($save, $Value);
fclose($save);
}
the problem is when I try to write on the file. I got only one line.what is my error.
You are calling fclose() on the file in your loop that is writing records. fclose() closes the file handle so it is no longer valid and cannot be written to.
Move fclose($save); after the } that ends the foreach() with your content.
Also, you could simplify things a bit by calling $Content = file_get_contents($File); since that is what you are doing in effect with fread(). Also, since $File is just a string variable, calling fclose() on it is unnecessary and doesn't do anything. You were correctly closing it by calling fclose() on $Handle. But using file_get_contents() will eliminate the need for both. The only file you would need is the one you were writing to.
Here is an example using the file() function which reads each line of a file into an array.
$file = '/var/apache2/htdocs/loginS/host.txt';
$content = file($file);
$save = fopen('./out.csv', 'w+');
foreach($content as $line) {
$line = rtrim($line, "\r\n"); // remove the newline from $line
$parts = explode("\t", $line);
$lineCsv = implode('|', $parts); // or ',' ?
fwrite($save, $lineCsv . "\n"); // write output to file
}
fclose($save);

How to correctly use the PHP function 'fgets'?

I assume I'm using the fgets() wrong. I'm tring to open a PHP file and then try to match a line in that file with a variable I create. If the line does match then I want to write/insert PHP code to the file right below that line. Example:
function remove_admin(){
$findThis = '<tbody id="users" class="list:user user-list">';
$handle = #fopen("../../fns-control/users.php", "r"); // Open file form read.
if ($handle) {
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 479); // Read a line.
if ($buffer == '<tbody id="users" class="list:user user-list">') // Check for string.
{
Now I want to write PHP code to the file, starting on line 480. How can I do that?
Useful information may be: IIS 6 and PHP 5.2.
Try this:
<?php
function remove_admin(){
$path = "../../fns-control/users.php";
$findThis = '<tbody id="users" class="list:user user-list">';
$phpCode = '<?php echo \'hello world\'; ?>';
#Import file to string
$f = file_get_contents($path);
#Add in the PHP code
$newfile = str_replace($findThis, $findThis . $phpCode, $f);
#Overwrite the existing file
$x = fopen($path, 'w');
fwrite($x, $newfile);
fclose($x);
}

Categories