PHP - while loop (!feof()) isn't outputting/showing everything - php

I am trying to read (and echo) everything of a .txt-File.
This is my code:
$handle = #fopen("item_sets.txt", "r");
while (!feof($handle))
{
$buffer = fgets($handle, 4096);
$trimmed = trim($buffer);
echo $trimmed;
}
This is my "item_sets.txt": http://pastebin.com/sxapZGuW
But it doesn't echo everything (and changing how much it shows depending on if and how many characters i echo after it). var_dump() shows me that the last string is never finished printing out. That looks like this:
" string(45) ""[cu_well_tra. But if I put an
echo "whateverthisisjustarandomstringwithseveralcharacters";,
my last output lines look like this:
" string(45) ""[cu_well_traveled_ak47]weapon_ak47" "1"
" string(5) "}
"
Basically my code isn't printing/echoing all of what it should or at least not showing it.
Thanks in advance :)

Thats because your test for EOF is before you output your last read
Try this with the test for EOF as part of the reading process
<?php
$line_count = 0;
$handle = fopen("item_sets.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$trimmed = trim($buffer);
echo $trimmed;
$line_count++;
}
} else {
echo 'Unexpected error opening file';
}
fclose($handle);
echo PHP_EOL.PHP_EOL.PHP_EOL.'Lines read from file = ' . $line_count;
?>
Also I removed the # infront of the fopen its bad practice to ignore errors, and much better practice to look for them and deal with them.
I copied your data into a file called tst.txt and ran this exact code
<?php
$handle = fopen('tst.txt', 'r');
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$trimmed = trim($buffer);
echo $trimmed;
}
} else {
echo 'Unexpected error opening file';
}
fclose($handle);
And it generated this output ( just a small portion shown here )
"item_sets"{"set_community_3"{"name" "#CSGO_set_community_3""set_description" "#CSGO_set_community_3_desc""is_collection"
And the last output is
[aa_fade_revolver]weapon_revolver" "1"
Which is the last entry in the data file

Related

Search for text in a 5GB+ file then get whole line

I want to search for the text Hello (example) in a TXT file whose size is 5GB+ then return the whole line.
I've tried using SplFileObject but what I know is that the line number is required to use SplFileObject, like that:
$linenumber = 2094;
$file = new SplFileObject('myfile.txt');
$file->seek($linenumber-1);
echo $file->current();
But as previously mentioned, I want to search for a string then get the whole line, I don't know the line number.
Any help would be appreciated.
this should work:
<?php
$needle = 'hello';
$count = 1;
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
$pos = strpos($line, $needle);
if ($pos !== false) {
echo $line . PHP_EOL;
echo "in line: ".$count . PHP_EOL;
break;
}
$count++;
}
fclose($handle);
} else {
// error opening the file.
}
This is the answer that I can use. Thanks a lot to #user3783243
For Linux:
exec('grep "Hello" myfile.txt', $return);
For Windows:
exec('findstr "Hello" "myfile.txt"', $return);
Now $return should contain the whole line.
Unfortunately, this doesn't work if exec() and system() functions are disabled by your server administrator in the php.ini file. But for me it works fine.
If someone have a better solution I'd be glad to know it :)

fgetCsv Returning null values for csv file in php

I have a csv file placed at path
#http://thevowapp.com/brandstore/values.csv
$f = fopen("http://thevowapp.com/brandstore/values.csv", "w+");
if(!f)
{
echo "Error";
}
$line = fgetcsv($f);
echo json_encode($line);
I am trying to parse it, however the fgetCsv keeps on returning null. What could be the error?
Problems:
You try to open a remote file with w+ (write) access. Use r for read.
You check f (undefined constant). Use$f`.
You don't loop fgetcsv, so you won't get more than the header line.
Try:
$f = fopen('http://thevowapp.com/brandstore/values.csv', 'r');
if(!$f) {
echo 'Error';
exit;
}
$out = array();
while ($line = fgetcsv($f)) {
$out[] = $line;
}
echo json_encode($out, JSON_PRETTY_PRINT);
Remove the pretty print option when you're happy.

Why is str_replace not working correctly

In my directory I have a list.csv of the form:
RP2015, active
Hope, paused
Process99, active
I'm writing a php script to allow a web user to switch the different lines from 'active' to 'paused' and back. Unfortunately I've hit a snag. My current code is live at: http://whitewaterwriters.com/Driver/index.php
and it looks like this
<HTML>
<Body>
<?
if ($_POST != null) {
$target = $_POST ['sprint'];
echo "<br>Target was:".$target;
$replacement=str_replace('active','paused',$target);
if (strpos($target,'paused') !== false) {
$replacement=str_replace('paused','active',$target);
}
echo "<br>Replacement was:".$replacement."<br>";
$filename = "list.csv";
$contents = file_get_contents($filename);
print "<br>contents was:".$contents;
$new_contents = str_replace($target, $replacement, $contents);
print "<br>contents became:".$new_contents;
file_put_contents($filename, $new_contents);
}
?>
<br><br>
<?php
$row = 1;
if (($handle = fopen("list.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo '<form action="index.php" method=post>';
echo $data[0] . $data[1];
echo '<button type="submit" value="'. $data[0].", ".$data[1].'" name="sprint">Pause</button></form><br>';
}
fclose($handle);
}
?>
</body>
</html>
For some reason the replace is not firing. The event is captured, the correct target and replace strings are (I think) generated, but the replace is NOT coming out. The output I get is:
Target was:RP2015, active
Replacement was:RP2015, paused
contents was:RP2015, active
contents became:RP2015, active
RP2015 active
Can anyone tell me what's going on?
EDIT:
The current list.csv is exactly:
RP2015, active
`
Try this:-
$fp = fopen($filename, "wb");
$handle = fopen($filename, "wb");
$replacement = str_replace("active", "paused", $fp);
$numbytes = fwrite($handle, $replacement);
fclose($handle);
The thing I had forgotten is that html squashes consecutive spaces together which is why the $target looked like it was fine. Actually:
$data[0].", ".$data[1]
only needed to be
$data[0].",".$data[1]
Because there was a space left over from the csv parsing. I'll make the code a bit more robust to that in future.
For the interested - this helper function I wrote helped me locate the error:
function toask($inStr){
$arr1 = str_split($inStr);
foreach ( $arr1 as $a){
print ord($a)." ";
}
}
It converts a string to a sequence of ascii codes do you can make sure, for example, that quote characters are the ones you think they are...

print contents of file until found the word hi

I want the program to print the document contents line by line while not reaching neither the end of file or found the word hi
The problem is when it found the word hi, it prints nothing although it is at position 22. Why not print the previous words how to solve this issue.
My file contain "Php is a special case hi. You will use less memory using the iterative solution. Moreover, function calls in PHP are costly, so it's better to avoid function calls when you can." string.
Here is my code
<?php
$contents = file_get_contents('m.txt');
$search_keyword = 'hi';
// check if word is there
$file=fopen("m.txt","r+");
while(!feof($file)&&strpos($contents, $search_keyword) == FALSE)
{
echo fgets($file)."<br>";
}
?>
change this condition
while(!feof($file)&&strpos($contents, $search_keyword) == FALSE)
to
while(!feof($file)) {
if(strpos($contents, $search_keyword) === FALSE) {
echo fgets($file)."<br>";
} else
break;
}
}
You mean print the file line by line until the word 'hi' is found?
<?php
$search_keyword = 'hi';
$handle = #fopen("m.txt", "r");
if ( $handle )
{
// Read file one line at a time
while ( ($buffer = fgets($handle, 4096)) !== false )
{
echo $buffer . '<br />';
if ( preg_match('/'.$search_keyword.'/i', $subject) )
break;
}
fclose($handle);
}
?>
You can replace the preg_match to strpos if you like.

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.

Categories