PHP for read txt file line just upon sign "#" - php

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

Related

Trying to hash all strings in the file after the comma separator

I have a file with keywords on each line. The line starts with number then comma and after that the keyword (like comma separated csv but text file). The file looks like this
7,n00t
41,n01
13,n021
21,n02
18,n03
13,n04
15,n05
13,n06
18,n07
13,n08
14,n09
9,n0a
What I'm trying is to run whole file and hash only the keywords without the number before the comma.
What I'm tried is this.
$savePath = "test-file.txt";
$handle = fopen($savePath, "r+");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$hash1 = substr($line, strpos($line, ",") + 1);
$hash2 = hash('ripemd160', $hash1);
fwrite($handle, $hash2);
}
fclose($handle);
} else {
echo "Can't open the file!";
}
It is working but the problem is that it is hashing the number before the comma and on most of the lines I get one string. This is the output
d743dcc66de14a3430d806aad64a67345fd0b23d0007
75f32ebf42e3ffd70fc3f63d3a61fc6af0075c24000088
7b816ac9cbe2da6a6643538564216e441f55fe9f6,00009
f0ba52b83ffac69fddd8786d6f48e7700562f0170b
def75b09e253faea412f67e67a535595b00366dce
c0da025038ed83c687ddc430da9846ecb97f3998l
c0da025038ed83c687ddc430da9846ecb97f39985,0000r
c12530b4b78bde7bc000e4f15a15bcea013eaf8c
9c1185a5c5e9fc54612808977ee8f548b2258d31,00010
efa60a26277fde0514aec5b51f560a4ba25be3c111
0e25f9d48d432ff5256e6da30ab644d1ca726cb700123
ad6d049d794146aca7a169fd6cb3086954bf2c63012
Should be
7,d743dcc66de14a3430d806aad64a67345fd0b23d0007
41,75f32ebf42e3ffd70fc3f63d3a61fc6af0075c24000088
13,7b816ac9cbe2da6a6643538564216e441f55fe9f6,00009
21,f0ba52b83ffac69fddd8786d6f48e7700562f0170b
18,def75b09e253faea412f67e67a535595b00366dce
13,c0da025038ed83c687ddc430da9846ecb97f3998l
15,c0da025038ed83c687ddc430da9846ecb97f39985,0000r
13,c12530b4b78bde7bc000e4f15a15bcea013eaf8c
18,9c1185a5c5e9fc54612808977ee8f548b2258d31,00010
13,efa60a26277fde0514aec5b51f560a4ba25be3c111
14,0e25f9d48d432ff5256e6da30ab644d1ca726cb700123
9,ad6d049d794146aca7a169fd6cb3086954bf2c63012
Any ideas what is the problem?
The thing is you are reading and writing to the file at the same time. This way, internal pointer is being juggled all the time. Instead, read all the lines, store the result in an array and fseek the file pointer to the beginning of the file again and keep writing the new lines one by one as shown below.
Snippet:
<?php
$handle = fopen("test-file.txt", "r+");
if (!$handle) {
throw new Exception("Can't open file!");
}
$newLines = [];
while (($line = fgets($handle)) !== false) {
$hash = hash('ripemd160', substr($line, strpos($line, ",") + 1));
$newLines[] = substr($line, 0, strpos($line, ",")) . "," . $hash;
}
fseek($handle, 0);
foreach($newLines as $line){
fwrite($handle, $line . "\n");
}
fclose($handle);
The trouble is twofold:
You're trying to write to the file you're reading, while you're reading it without even changing the position of the file pointer, and vice-versa for the reads.
You're trying to overwrite 3-4 bytes of data with 32 bytes of data, which ends up clobbering most of the rest of the input you're trying to read.
If you want to change a file like this you need to create a new file, write your data to that, and then rename the new file to the old one.
Also, use fgetcsv() and fputcsv() to read and write CSV files, otherwise you're going to wind up fighting with edge cases when your input data starts getting complex.
$savePath = "test-file.txt";
$in_h = fopen($savePath, "r+");
$out_h = fopen($savePath.'.new', 'r+');
if ($in_h) {
while (($line = fgetcsv($in_h)) !== false) {
$line[1] = hash('ripemd160', $line[1]);
fputcsv($out_h, $line);
}
fclose($in_h);
fclose($out_h);
rename($savePath.'.new', $savePath);
} else {
echo "Can't open the file!";
}

create multiple directories using loop in php

I am taking data from text file( data is: daa1 daa2 daa3 on separate lines) then trying to make folders with exact name but only daa3 folders is created. Also when i use integer it creates all folders, same is the case with static string i.e "faraz".
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$line =0;
while ( $line < 5 )
{
$a = fgets($f, 100);
$nl = mb_strtolower($line);
$nl = "checkmeck/".$nl;
$nl = $nl."faraz"; // it works for static value i.e for faraz
//$nl = $nl.$a; // i want this to be the name of folder
if (!file_exists($nl)) {
mkdir($nl, 0777, true);
}
$line++;
}
kindly help
use feof function its much better to get file content also line by line
Check this full code
$file = __DIR__."/dataFile.txt";
$linecount = 0;
$handle = fopen($file, "r");
$mainFolder = "checkmeck";
while(!feof($handle))
{
$line = fgets($handle);
$foldername = $mainFolder."/".trim($line);
//$line is line name daa1,daa2,daa3 etc
if (!file_exists($foldername)) {
mkdir($foldername, 0777, true);
}
$linecount++;
unset($line);
}
fclose($handle);
output folders
1countfaraz
2countfaraz
3countfaraz
Not sure why you're having trouble with your code, but I find it to be more straightforward to use file_get_contents() instead of fopen() and fgets():
$file = __DIR__."/dataFile.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents);
foreach ($lines as $line) {
$nl = "checkmeck/". $line;
if (!file_exists($nl)) {
echo 'Creating file '. $nl . PHP_EOL;
mkdir($nl, 0777, true);
echo 'File '. $nl .' has been created'. PHP_EOL;
} else {
echo 'File '. $nl .' already exists'. PHP_EOL;
}
}
The echo statements above are for debugging so that you can see what your code is doing. Once it is working correctly, you can remove them.
So you get the entire file contents, split it (explode()) by the newline character (\n), and then loop through the lines in the file. If what you said is true, and the file looks like:
daa1
daa2
daa3
...then it should create the following folders:
checkmeck/daa1
checkmeck/daa2
checkmeck/daa3

code was working, but suddenly stopped working

This code opens a text file, then checks to see if each word in the text file
Exists in a another large 2MB dictionary file.
If it does exist, it stores the line from the dictionary file into a variable.
The code was working, but then began to generate Server 500 errors, and now
It only lists about 7 matches and then loads nothing forever.
It used to list the 1000's of matches and then stop.
$file_handle = fopen("POSdump.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$words= explode(" ", $line );
foreach ($words as $word) {
$word = preg_replace('#[^\w+>\s\':-]#', ' ', $word);
$subwords= explode(" ", $word );
$rawword = $subwords[0];
$poscode = $subwords[1];
$rawword = strtoupper($rawword);
$handle = fopen("dictionary.txt","r"); //
if ($handle) {
while (!feof($handle))
{
$buffer = fgets($handle, 4096);
if (preg_match('#\b'.$rawword.'\b#',$buffer)) {
echo $rawword;
echo "</br>";
}
}
}
}
}
?>
Try closing the file when you are done.
This seems to be a memory_limit error. use ini_set('memory_limit', -1) before starting the process.

Sort the unsorted text file and rewrite to same text file in sorted order

I have a question. I am in process of learning how to read/write files, but having little trouble trying to do both at the same time in same php script. I have a text file with words like this,
Richmond,Virginia
Seattle,Washington
Los Angeles,California
Dallas,Texas
Jacksonville,Florida
I wrote a code to sort them in order and this will display in sort order by City.
<?php
$file = file("states.txt");
sort($file);
for($i=0; $i<count($file); $i++)
{
$states = explode(",", $file[$i]);
echo $states[0], $states[1],"<br />";
}
?>
From this, how can I rewrite those sorted information back into the states.txt file?
The easiest way to write the contents of $file back to the file would be using file_put_contents in collaboration with implode.
file_put_contents("states.txt", implode($file));
Try using fopen and fwrite.
$fileWrite = fopen("filePah", "w");
for($i=0; $i<count($file); $i++)
{
fWrite($fileWrite, $file[i]);
}
fClose($fileWrite);
<?php
$file = file("states.txt");
sort($file);
$newContent = "";
for($i=0; $i<count($file); $i++)
{
$states = explode(",", $file[$i]);
$newContent .= $states[0] .', '. $states[1] . PHP_EOL;
}
file_put_contents('states.txt',$newContent);
?>
PHP: file_put_contents
Try something like this:
$fo = fopen("filename", "w");
$content = "";
for ($i = 0; $i < count($file); $i++) {
$states = explode(",", $file[$i]);
$content .= $states[0] . "," . $states[1] . "\n";
}
fwrite($fo, $content);
fclose($fo);
this is a little extended, however I thought it might be useful to smb. I have an m3u playlist and need only particular rows filtered, sorted and printed. Credits go to Devil:
<?php
//specify that the variable is of type array
$masiv = array();
//read the file
$file = '/home/zlobi/radio/pls/all.m3u';
$f = fopen($file, "r");
while ($line = fgets($f))
{
//skip rows with #EXT
if(strpos($line, "#EXT") !== false) continue;
$text = str_replace('.ogg', ' ', $line);
$text = str_replace('/home/zlobi/radio/',' ',$text);
//add the song as an element in an array
$masiv[] = $text;
}
$f = fclose($f);
//sort the array
sort($masiv);
//pass via the array, take each element and print it
foreach($masiv as $pesen)
print $pesen.'<br/>';
?>
masiv is array, pesen is song in Bulgarian :)
CAPital letters are sorted first.
Regads
Once you are done reading the file into the array by a call to file. You can open the file for writing by using the fopen function, write into the file using the fwrite and close the file handle using fclose:
<?php
$file = file("states.txt"); // read file into array.
$fh = fopen('states.txt','w') or die("..."); // open same file for writing.
sort($file);
for($i=0; $i<count($file); $i++)
{
$states = explode(",", $file[$i]);
echo $states[0], $states[1],"<br />";
fwrite($fh,"$states[0],$states[1] <br />"); // write to file.
}
fclose($fh); // close file.
?>
Open the file, write to it, close it (this assumes $file is the variable from your code):
$fp = fopen('states.txt', 'w');
for($i=0; $i<count($file); $i++)
fwrite($fp, $file[$i]);
}
fclose($fp);
And see http://php.net/manual/en/function.fwrite.php
This is by far the fastest and most elegant solution that I have found, when I had the same problem.
If you're on Linux (with exec allowed in PHP configuration) you can do the following (provided you want to sort files numerically):
exec("sort -n " . $pathToOriginalFile . " > " . $pathToSortedFile);
Basically, execute bash command sort that sorts the lines in a file numerically.
If you want to keep the data in the original file do this:
exec("sort -n " . $pathToOriginalFile . " > " . $pathToSortedFile);
exec("rm " . $pathToOriginalFile);
exec("mv " . $pathToSortedFile . " " . $pathToOriginalFile);
If you want an alphabetical sort just exclude -n (--numeric-sort) option.
exec("sort " . $pathToOriginalFile . " > " . $pathToSortedFile);
For me the command took about 3 seconds to sort 10 million lines in the file on the server.
You can find more about sort here http://www.computerhope.com/unix/usort.htm
Hope it helps.

Text file into an array?

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.

Categories