In php how can I read a text file and get each line into an array?
I found this code which does it, somewhat, but looks for a = sign and I need to look for a new line:
<?PHP
$file_handle = fopen("dictionary.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode('=', $line_of_text);
print $parts[0] . $parts[1]. "<BR>";
}
fclose($file_handle);
?>
Well, you could just replace the '=' with a "\n" if the only difference is that you're looking for a newline.
However, a more direct way would be to use the file() function:
$lines = file("dictionary.txt");
That's all there is to it!
Use php's file function:
file — Reads entire file into an array
Example:
$lines = file('dictionary.txt');
echo $lines[0]; //echo the first line
So, use the character for a newline instead of the '='
'\n'
Rather than using '=', use '\n'.
Example (also strips '\r' characters, for files which use '\r\n' as their line delimiter):
<?PHP
$file_handle = fopen("dictionary.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$line_of_text = str_replace('\r', '', $line_of_text);
$parts = explode('\n', $line_of_text);
print $parts[0] . $parts[1]. "<BR>";
}
fclose($file_handle);
?>
Note: This code example won't work on files which use '\r' by itself to specify newlines.
Related
The numbers in my file are 5X5:
13456
23789
14789
09678
45678
I'm trying to put it into this form
array[0]{13456}
array[1]{23789}
array[2]{14789}
array[3]{09678}
array[4]{45678}
My code is:
$fileName = $_FILES['file']['tmp_name'];
//Throw an error message if the file could not be open
$file = fopen($fileName,"r") or exit("Unable to open file!");
while ($line = fgets($file)) {
$digits .= trim($line);
$members = explode("\n", str_replace(array("\r\n","\n\r","\r"),"\n",$digits));
echo $members;
The output I'm getting is this:
ArrayArrayArrayArrayArray
fgets gets a line from the file pointer, so theoretically there should be no "\r" or "\n" characters in $line. explode will still work, even if the delimiter is not found. You'll just end up with an array with one item, the entire string. You can't echo an array, though. (That's why you're seeing Array for each line; it's the best PHP can do when you use echo on an array.)
If I were you, I would rather just use file() instead.
$members = array_map('trim', file($fileName, FILE_IGNORE_NEW_LINES));
With the example file you showed, this should result in
$members = ['13456', '23789', '14789', '09678', '45678'];
You can simply put the lines into an array and use print_r instead of echo to print that array
while ($line = fgets($file)) {
$members[] = $line;
}
print_r($members);
It should depend on the file that you are dealing with.
FileType:
text -> fgets($file)
CSV -> fgetcsv($file)
I am using PHP to read a simple text file with the fgets() command:
$file = fopen("filename.txt", "r") or exit('oops');
$data = "";
while(!feof($file)) {
$data .= fgets($file) . '<br>';
}
fclose($file);
The text file has leading white spaces before the first character of each line. The fgets() is not grabbing the white spaces. Any idea why? I made sure not to use trim() on the variable. I tried this, but the leading white spaces still don't appear:
$data = str_replace(" ", " ", $data);
Not sure where to go from here.
Thanks in advance,
Doug
UPDATE:
The text appears correctly if I dump it into a textarea but not if I ECHO it to the webpage.
Function fgets() grabs the whitespaces. I don't know what you are exactly doing with the $data variable, but if you simply display it on a HTML page then you won't see whitespaces. It's because HTML strips all whitespaces. Try this code to read and show your file content:
$file = fopen('file.txt', 'r') or exit('error');
$data = '';
while(!feof($file))
{
$data .= '<pre>' . fgets($file) . '</pre><br>';
}
fclose($file);
echo $data;
The PRE tag allows you to display $data without parsing it.
Try it with:
$data = preg_replace('/\s+/', ' ', $data);
fgets should not trim whitespaces.
Try to read the file using file_get_contents it is successfully reading the whitespace in the begining of the file.
$data = file_get_contents("xyz.txt");
$data = str_replace(" ","~",$data);
echo $data;
Hope this helps
I currently have the same requirement and experienced that some characters are written as a tab character.
What i did was:
$tabChar = ' ';
$regularChar = ' '
$file = fopen('/file.txt');
while($line = fgets($file)) {
$l = str_replace("\t", $tabChar, $line);
$l = str_replace(" ", $regularChar, $line);
// ...
// replacing can be done till it matches your needs
$lines .= $l; // maybe append <br /> if neccessary
}
$result = '<pre'> . $lines . '</pre>';
This one worked for me, maybe it helps you too :-).
I have a php program that looks at a log file and prints it to a page (code below). I don't want the user of said website to be able to look at any line containing a /. I know I could use trim to delete certain characters, but is there a way to delete the entire line? For example, I want to keep something like "Hello" and delete something like /xx.xx.xx.xx connected. All the lines I wish to delete have the same common key, /. Peoples names in said log file have <>s around them, so I must use htmlspecialcharacters
$file = file_get_contents('/path/to/log', true);
$file = htmlspecialchars($file);
echo nl2br($file);
Thanks for your help!
EDIT:
Thanks for all of the answers, currently tinkering with them!
EDIT2:
final code:
<?php
$file = file_get_contents('/path/to/log', true);
// Separate by line
$lines = explode(PHP_EOL, $file);
foreach ($lines as $line) {
if (strpos($line, '/') === false) {
$line = htmlspecialchars($line . "\n");
echo nl2br($line);
}
}
?>
Do you mean, like this?
$file = file_get_contents('/path/to/log', true);
// Separate by line
$lines = explode(PHP_EOL, $file);
foreach ($lines as $line) {
if (strpos($line, '/') === false) {
// If the line doesn't contain a "/", echo it
echo $line . PHP_EOL;
}
}
For anyone wondering, PHP_EOL is the PHP constant for "end of line" and promotes consistency between different systems (Windows, UNIX, etc.).
If you are iterating through the file line by line you can check with preg_match if the line contains /character and skip the echo if it does. If not, first split them at new line and iterate over that array.
If you don't want to split the file you can probably use preg_replace with a regexp such as (^|\n).*/.*(\n|$) and replace with empty string.
Use the str_replace function -
http://php.net/manual/en/function.str-replace.php. Alternate solution (before escaping the special characters) -
/* pattern /\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\sconnected/ = /xx.xx.xx.xx connected */
/* pattern will be replaced with "newtext" */
$file = file_get_contents("/path/to/log", true);
$lines = explode("\n", $file);
foreach ($lines as $line)
$correctline = preg_replace( '/\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\sconnected/', 'newtext', $line );
echo $correctline;
}
<?php
$file = file_get_contents("/path/to/log", true);
$lines = explode("\n", $file);
foreach ($lines AS $num => $line)
{
if ( strpos($line, "/") === false ) // Line doesn't contain "/"
{
echo htmlspecialchars($line) . "\n";
}
}
?>
there is text in file as example:
<div class="from">jack</span></div>
hey u
<div class="from">ron</span></div>
bye
i am trying to delete the new line tag after "" and replace "|"
the result i need is:
<div class="from">jack</span></div>|hey u
<div class="from">ron</span></div>|bye
i tried this but think i got it wrong because it do the job.
$string = file_get_contents($filename);
$string = str_replace('/(<\/span><\/div>\r\n)', '|', $string);
file_put_contents($filename, $string);
what is the correct way?
thanks
<?php
$string = '<div class="from"><span>jack</span></div>
hey u';
echo preg_replace('/\r\n/', '|', $string);
$file_handle = fopen($filename, "r");
$text = "";
while (!feof($file_handle)) {
$line = fgets($file_handle);
if (strpos($line,'<div>') !== false) {
$line = preg_replace('/\r\n/', '|', $line)
}
$text .= $line;
}
file_put_contents($filename, $text);
fclose($file_handle);
Hows that for reading the file line by line, if the line has a tag, it replaces \n\r, and then at the end writes all of the lines back into the file.
It depends on what line ending is used, there's three possible ones, \n, \r\n, and \r.
Try this:
$string = str_replace('/(<\/span><\/div>\n)', '|', $string);
Also the first slash in that string is suspect, so try this:
$string = str_replace('(<\/span><\/div>\r\n)', '(<\/span><\/div>|', $string);
I have this txt file structure:
"data";"data";"data";#;"my data";"my data";"my data"
"data";"data";"data";#;"my data";"my data";"my data"
"data";"data";"data";#;"my data";"my data";"my data"
I need to read this file data just after the # sign.
My PHP code just for read the entire line.
$file_handle = fopen("texto.txt", "r");
$numlinha = 0;
while (!feof($file_handle)) {
$line = fgets($file_handle);
$numlinha++;
echo $numlinha . ". " . $line . "</br></br>";
}
fclose($file_handle);
You can use strpos function to find position of first # char in your line.
$file_handle = fopen("texto.txt", "r");
$numlinha = 0;
while (!feof($file_handle)) {
$line = fgets($file_handle);
$cpos = strpos($line, '#');
if ($cpos !== FALSE) {
$line = substr($line, 0, $cpos);
}
$numlinha++;
echo $numlinha . ". " . $line . "</br></br>";
}
fclose($file_handle);
$file_handle = fopen("texto.txt", "r");
$numlinha = 0;
while (!feof($file_handle)) {
$line = fgets($file_handle);
$parts = explode("#", $line);
$parts[0] // part before the # in this line
$parts[1] // part behind the # in this line
$numlinha++;
echo $numlinha . ". " . $line . "</br></br>";
}
fclose($file_handle);
You could use:
$data = explode(";#;", $line);
And then do your processing on $data[1] instead of $line.
This assumes that ;#; is unique on each line...
Note that using string position testing (strpos()) and substr() to extract the part of the string would be more resource consuming, I believe, than just taking the line you already read and splitting it at the exact known delimiter, which in this case is ;#;.
The other examples posted assume that # will be only on the line once, or at least the divide will be the first # in the line. Using ;#; would make it more unique, and your result can be processed by the str_getcsv() function if you needed to break it down into an array of values for other uses.
You can use the explode function, to split the string in two parts using the "#" delimiter
http://php.net/function.explode