PhP - How to place different strings into repeating embedding text? - php

OK so let's say I have a .txt file with the following lines:
Mark
Jane
Ann
How could I make a php code which reads these names line by line and then saves them in a new text file like this:
Hi my name is Mark, what's yours?
Hi my name is Jane, what's yours?
hi my name is Ann, what's yours?
P.S - This is a simplified version of my problem, I actually have a list of URLs that I need to sorround by some XML code and then stack those one on top of another, so it turns out to be one big XML file. The surrounding blocks of XML text are static, they don't change, the only thing that should change is the part where the URL needs to be inserted, of course.

How about this: (result.txt contains your result, and input.txt contains your names)
<?php
$filename = "result.txt";
if (!$handleRes = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
$handle = #fopen("input.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
fwrite($handleRes, "Hi my name is ".chop($buffer).", what's yours?\n");
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>

$aString = file_get_contents("text.txt"); // get text from file
$aString = explode("\n", $aString); // split this text with new line character
$aString = array_map('trim',$aString); // remove spacing between left and right
foreach($aString as $index => $strString){ // browse each line
$aString[$index] = "Hi my name is $strString, what's yours?"; // change to new format
}
$aString = implode("\r\n", $aString); // join array to string
echo $aString;

Open the file, and then read.
$names = file("names.txt");
foreach ($names as $name) {
printf("Hi My name is %s, What's yours?\n", $name);
}

Related

PHP Replace all values in the third column in a csv file

I am trying to replace some hyperlinks in a csv file, like this one:
[https://assets.suredone.com/683987/media-pics/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. Here is my code:][1]. Here is my code:
<?php
$in_file = 'gabriel-images-urls.csv';
$out_file = 'results.csv';
$fd = fopen($in_file, "r");
$new_array= array();
$toBoot= array();
while ($data = fgetcsv($fd)) {
echo '<pre>';
if (strpos($data[2],'media-pics') !== false) {
$data[2]=str_replace('media-pics','media-photos',$data[2]);
fputcsv($fd, $data);
// echo $output;
}
}
?>
The new link for example must look like this:[1]https://assets.suredone.com/683987/media-photos/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. The goal is he "media-pics" substring to be replaced with "media-photos". At this point nothing happens in the file. I think this is because the file is open only for reading but I am not sure.
Can you not simply do a string replacement on the whole file rather than attempting to load and process each line of the file using fgetcsv?
<?php
$srcfile='gabriel-images-urls.csv';
$outfile='results.csv';
$csvdata=file_get_contents( $srcfile );
$moddata=str_replace('media-pics','media-photos',$csvdata);
file_put_contents( $outfile, $moddata );
?>

PHP opening a large file

What's the best way to read a .TXT file (The file size is 225mb). I want to open the file and loop thru it and find information via REGEX.
Example data in the file :
00424333060001410100100BILLLLOYD BRRUSSELL & 12675 MAKALISO AVE WEST WORKS TOWN KS 23456-1035 3341310350630200500004200000001887800001789IWD QM1214200400003367250001799900001287IWD QM 000000000000000000000000000000 000000000000000000000000000000
The problem I am having is the file taking forever to open. And to search thru takes a while. My loop could have 75 items I need to search.
$name2 = "BILLLLOYD BRRUSSELL ";
$RE21 = "/[0-9]{23}.$name2/";
$file = fopen("MYFILE.TXT", "r");
while(!feof($file)){
$line = fget($file);
for ($row = 0; $row = 75; $row++{
$name2 = data i am getting from another file...;
$RE21 = "/[0-9]{23}.$name2/"; //Not sure if this works!!
$a = preg_match($RE21, $line, $matches);
foreach($matches as $x => $x_value) {
I will $x_value and store it.} //$x_value should be 00424333060001410100100BILLLLOYD BRRUSSELL
} //foreach
} //for
}//while
fclose($file);
Maybe you should try a different approach and use command line grep? Generate the regexps from your "another file" and the execute a grep command using your generated pattern and the file you want to search?
Use the -o flag to only get your matches from the result
You can read it line by line:
$handle = fopen("bla.txt", "r");
while (($buffer = fgets($handle, 4096)) !== false) {
// ...
}
fclose($handle);

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....

PHP: Read Specific Line From File

I'm trying to read a specific line from a text file using php.
Here's the text file:
foo
foo2
How would I get the content of the second line using php?
This returns the first line:
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
..but I need the second.
Any help would be greatly appreciated
$myFile = "4-24-11.txt";
$lines = file($myFile);//file in to an array
echo $lines[1]; //line 2
file — Reads entire file into an array
omg I'm lacking 7 rep to make comments. This is #Raptor's & #Tomm's comment, since this question still shows up way high in google serps.
He's exactly right. For small files file($file); is perfectly fine. For large files it's total overkill b/c php arrays eat memory like crazy.
I just ran a tiny test with a *.csv with a file size of ~67mb (1,000,000 lines):
$t = -microtime(1);
$file = '../data/1000k.csv';
$lines = file($file);
echo $lines[999999]
."\n".(memory_get_peak_usage(1)/1024/1024)
."\n".($t+microtime(1));
//227.5
//0.22701287269592
//Process finished with exit code 0
And since noone mentioned it yet, I gave the SplFileObject a try, which I actually just recently discovered for myself.
$t = -microtime(1);
$file = '../data/1000k.csv';
$spl = new SplFileObject($file);
$spl->seek(999999);
echo $spl->current()
."\n".(memory_get_peak_usage(1)/1024/1024)
."\n".($t+microtime(1));
//0.5
//0.11500692367554
//Process finished with exit code 0
This was on my Win7 desktop so it's not representative for production environment, but still ... quite the difference.
If you wanted to do it that way...
$line = 0;
while (($buffer = fgets($fh)) !== FALSE) {
if ($line == 1) {
// This is the second line.
break;
}
$line++;
}
Alternatively, open it with file() and subscript the line with [1].
I would use the SplFileObject class...
$file = new SplFileObject("filename");
if (!$file->eof()) {
$file->seek($lineNumber);
$contents = $file->current(); // $contents would hold the data from line x
}
you can use the following to get all the lines in the file
$handle = #fopen('test.txt', "r");
if ($handle) {
while (!feof($handle)) {
$lines[] = fgets($handle, 4096);
}
fclose($handle);
}
print_r($lines);
and $lines[1] for your second line
$myFile = "4-21-11.txt";
$fh = fopen($myFile, 'r');
while(!feof($fh))
{
$data[] = fgets($fh);
//Do whatever you want with the data in here
//This feeds the file into an array line by line
}
fclose($fh);
This question is quite old by now, but for anyone dealing with very large files, here is a solution that does not involve reading every preceding line. This was also the only solution that worked in my case for a file with ~160 million lines.
<?php
function rand_line($fileName) {
do{
$fileSize=filesize($fileName);
$fp = fopen($fileName, 'r');
fseek($fp, rand(0, $fileSize));
$data = fread($fp, 4096); // assumes lines are < 4096 characters
fclose($fp);
$a = explode("\n",$data);
}while(count($a)<2);
return $a[1];
}
echo rand_line("file.txt"); // change file name
?>
It works by opening the file without reading anything, then moving the pointer instantly to a random position, reading up to 4096 characters from that point, then grabbing the first complete line from that data.
If you use PHP on Linux, you may try the following to read text for example between 74th and 159th lines:
$text = shell_exec("sed -n '74,159p' path/to/file.log");
This solution is good if your file is large.
You have to loop the file till end of file.
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
Use stream_get_line: stream_get_line — Gets line from stream resource up to a given delimiter
Source: http://php.net/manual/en/function.stream-get-line.php
You could try looping until the line you want, not the EOF, and resetting the variable to the line each time (not adding to it). In your case, the 2nd line is the EOF. (A for loop is probably more appropriate in my code below).
This way the entire file is not in the memory; the drawback is it takes time to go through the file up to the point you want.
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$i = 0;
while ($i < 2)
{
$theData = fgets($fh);
$i++
}
fclose($fh);
echo $theData;
?>
I like daggett answer but there is another solution you can get try if your file is not big enough.
$file = __FILE__; // Let's take the current file just as an example.
$start_line = __LINE__ -1; // The same with the line what we look for. Take the line number where $line variable is declared as the start.
$lines_to_display = 5; // The number of lines to display. Displays only the $start_line if set to 1. If $lines_to_display argument is omitted displays all lines starting from the $start_line.
echo implode('', array_slice(file($file), $start_line, lines_to_display));
I searched for a one line solution to read specific line from a file.
Here my solution:
echo file('dayInt.txt')[1]

Search a file and migrate search term is in to a new file

This code enables to create a new .txt file, if the file doesn't exist yet, it will create the file.
<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
And this code here identifies each line of string into a token.
<?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well */
$tok = strtok($string, " \n\t");
while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" \n\t");
}
?>
The people.txt looks like this
John Smith
John Meyer
John Chase
John Smith //i want to transfer this set of string into a new file
What am i missing here?
$searchTerm = 'John Smith';
$file = 'people.txt';
$fileFound = 'peopleFound.txt';
$current = file_get_contents($file);
if (strpos($searchTerm, $current) !== false) {
file_put_contents($fileFound, $searchTerm."\n", FILE_APPEND);
}
$fp=fopen('people.txt','a+');
fputs($fp,"John Smith\r\n");
fclose($fp);
open and append the file, don't read it all in and append to the back and write it all back out. when the file gets past a certain size that will be real inefficient. I'm not sure how it is you're trying to tokenize it. seems to me you could just do a $names=file('people.txt'); and have them in an array immediately...

Categories