how do I read this text file in pieces? - php

hi I need to read a text file and then explode it to two piece then match it with give name then dispay if it matches...so far the code I made is given below..but it doesnt work..can any one tell me what wrong is with this code??
$name = "thomas";
$filename = file("land.txt");
//$contents = fread($handle, filesize($filename));
for($i=0; $i<count($filename); $i++)
{
$string = explode(":", $filename[$i]);
if($name == $string[1])
$id = $string[0];
}
echo $id;
this case it should display "D1"; but it doesnt!!
content of "land.txt" file
D1:thomas
D6:benny
D7:alwyn
D25:mathew
D9:peter

Try
$filename = file("land.txt", FILE_IGNORE_NEW_LINES);
Or
$string = explode(":", trim($filename[$i]));
What is FILE_IGNORE_NEW_LINES

Over here
if($name == $string[1]) use if($name == trim($string[1])) .
Try this and let me know.

$name = 'thomas';
$content = file('land.txt');
$id = NULL;
foreach($content as $no => $line){
$array = explode(':', $line);
if($array[1] == $name)
$id = $array[0];
}
echo $id;

Related

(PHP, AJAX) Simple counter. Figured the problem, no solution

Apologies for having to ask.
In short I'm making a simple imageboard with a "like" button for each image. The number of clicks (likes) stores in 'counter.txt' file in the following format:
click-001||15
click-002||7
click-003||10
Clicking the buttons initiates a small php code via AJAX. counter.php:
<?php
$file = 'counter.txt'; // path to text file that stores counts
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
$line = explode('||', fgets($fh));
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\r\n";
}
}
file_put_contents($file, $lines);
fclose($fh);
?>
So when I run the website and testclick my buttons I get the following message:
Notice: Undefined offset: 1 in C:\wamp64\www\wogue\counter.php on line
18
I figured that the script 'counter.php' creates a whitespace on a new string in 'counter.txt' and so it fails to 'explode' and thus make a [1] index. The way I figured that is by backspacing the last empty line in .txt file and saving it. It ran without errors until I clicked a button a few times then the same error appeared.
The piece of code in index looks like this:
<?php
$clickcount = explode("\n", file_get_contents('counter.txt'));
foreach($clickcount as $line){
$tmp = explode('||', $line);
$count[trim($tmp[0])] = trim($tmp[1]);
}
?>
Any ideas?..
Trim $line and if it is not empty - do what you need:
$line = trim(fgets($fh));
if ($line) {
$line = explode('||', $line);
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\r\n";
}
}
Or check with empty this way:
$line = explode('||', fgets($fh));
if(!empty(line[0]) && !empty($line[1])){
if(line[0] == $id){
$line[1]++; // increment count by 1
echo $line[1];
}
$lines .= "{$line[0]}||{$line[1]}\r\n";
}
}
You are writing using \r\n as a line separator in counter.php and reading the same file exploding only for \n. You should be consistent.
Just removing the \n should be enough to avoid the extra "space" you're seeing.
<?php
$file = 'counter.txt'; // path to text file that stores counts
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
$line = explode('||', fgets($fh));
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\n"; //removing the \r here
}
}
file_put_contents($file, $lines);
fclose($fh);
?>

How to update files in PHP

I have some PHP function that requires the line number of a CSV file used as database. Once it has line, it navigates to the specific value that needs to be changed, changes it and rewrites the whole files. Here is my code:
<?php
function update($file, $id, $field, $value)
{
//$id is the line number
$contents = explode("\n", file_get_contents($file));
$fh = fopen($file, "w");
$lines = array();
foreach($contents as $line)
{
if($line == "")
continue;
$fields = explode("|", $line);
if($fields[0] == $id)
{
$line = null;
for($i = 0; $i<count($fields); $i++)
{
if($i == $field)
$fields[$i] = $value;
if($i != count($fields)-1)
$line .= $fields[$i]."|";
else
$line .= $fields[$i];
}
}
$line .= "\n";
fwrite($fh, $line);
}
fclose($fh);
$contents = null;
return true;
}
$id = $_SESSION['id'];
$uid = $_GET['p'];
$myfile = "myfile.txt";
if(update($myfile, 12, 14, "somevalue"))
echo "updated!";
?>
I am unable to find the problem because whenever I run the code, it outputs "updated!" just as it should but when check the file, I find it has not been updated. I do not know why, but it always remains the same! Thanks.
Check that fwrite() is not failing.
Do something like this:
...
$writeSuccess = (fwrite($fh, $line) !== false);
}
fclose($fh);
$contents = null;
return $writeSuccess;
}
...
If it is failing, check that your filesystem permissions are correctly set. The Apache user needs to have write access to whatever file/folder you are writing the file to.
I found out what the problem was.
$id = $_SESSION['id'];
$uid = $_GET['p'];
$myfile = "myfile.txt";
if(update($myfile, 12, 14, "somevalue"))
The line number pointed to the previous line, which made it impossible to update the first line of the file. So all I had to do was
$line ++;

PHP Reading Lines from a Text File

I am trying to search a line in a text file and then print the following three lines. For example, if the text file has
1413X
Peter
858-909-9999
123 Apple road
then my PHP file would take in an ID ("1413X") through a form, compare it to lines in the text file - essentially a mock database - and then echo the following three lines. Currently, it is echoing only the phone number (with the second half of the numbers wrong??). Thanks for your help.
<?php
include 'SearchAddrForm.html';
$file = fopen("addrbook.txt", "a+");
$status = false;
$data = '';
if (isset($_POST['UserID']))
{
$iD = $_POST['UserID'];
$contact = "";
rewind($file);
while(!feof($file))
{
if (fgets($file) == $iD)
{
$contact = fgets($file);
$contact += fgets($file);
$contact += fgets($file);
break;
}
}
echo $contact;
}
fclose($file);
?>
It is better to set some flag that you found id and some counter to count lines after it to achieve your aim.
<?php
include 'SearchAddrForm.html';
// $file = fopen("addrbook.txt", "a+");
$file = fopen("addrbook.txt", "r");
$status = false;
$data = '';
if (isset($_POST['UserID']))
{
$iD = $_POST['UserID'];
$contact = "";
rewind($file);
$found = false;
$count = 1;
while (($line = fgets($file)) !== FALSE)
{
if ($count == 3) // you read lines you needed after you found id
break;
if ($found == true)
{
$contact .= $line;
$count++
}
if (trim($line) == $iD)
{
$found = true;
$contact = $line;
}
}
echo $contact;
}
fclose($file);
?>
This kind of example how you can achieve this. And as you see in comment you should use $contact .= value, not $contact += value.
Also instead of reading you can take the whole file in array line by line using function file.
And why are opening file for writing?
What I did:
<?php
//input (string)
$file = "before\n1413X\nPeter\n858-909-9999\n123 Apple road\nafter";
//sorry for the name, couldn't find better
//we give 2 strings to the function: the text we search ($search) and the file ($string)
function returnNextThreeLines($search, $string) {
//didn't do any check to see if the variables are not empty, strings, etc
//turns the string into an array which contains each lines
$array = explode("\n", $string);
foreach ($array as $key => $value) {
//if the text of the line is the one we search
//and if the array contains 3 or more lines after the actual one
if($value == $search AND count($array) >= $key + 3) {
//we return an array containing the next 3 lines
return [
$array[$key + 1],
$array[$key + 2],
$array[$key + 3]
];
}
}
}
//we call the function and show its result
var_dump(returnNextThreeLines('1413X', $file));

PHP get names in a file after letters name:

I need a PHP script to print customer names in a file. There's hundreds of names and addresses but I want to print only the names with a maximum of 15 letters.
<?php
$file = file_get_contents('data-cust.txt');
$keyword = 'name';
$str = substr($file, strpos($file, $keyword) + strlen($keyword), 15);
echo $str;
?>
I tried using the above but only printed one name. How do I make it print all names?
Thanks.
If the names are on their own line, something like this should work.
<?php
$file = file('data-cust.txt');
foreach($file as $line) {
$keyword = 'name';
$str = substr($line, strpos($line, $keyword) + strlen($keyword), 15);
echo $str;
}
You need to open the file and read it then extract the names.
$file = fopen("data-cust.txt", "r");
$keyword = 'name';
$str = array() ;
if ($file) {
while (($line = fgets($file )) !== false) {
$name = substr($line, strpos($line, $keyword) + strlen($line), 15);
echo $name ;
$str[] = $name ;
}
} else {
// error opening file
}
fclose($file );
print_r($str) ;

Weird characters jump out of arrays when used with get file contents

Hi this is a portion of my code which when ever output, the array $data2[0] seems to always output weird characters. It doesn't happens in $data2[1] or $data[2]..??? I been trying to figure this out for 2 days.
<?php
$filename = "../file/attendance_log/1414001189.txt";
$contents = file_get_contents($filename);
$contents = str_replace("\"","",$contents);
$lines = explode("\n", $contents);
$numrows = count($lines);
$x = 0;
for ($numrows; $x < $numrows; $x++)
{
echo $data2[0];
$data2 = explode(",", $lines[$x]);
echo $time = mktime(0,0,1,$data2[1],$data2[0],$data2[2]);
$user_no = $data2[3];
$item_no = $data2[4];
$quantity = $data2[5];
$waste = $data2[6];
$job_no = $data2[7];
}
?>
You're trying to explode and use the first line which has the column names in it
i slightly rewrote what you had to accomodate that and also not use a counter and
setting the default timezone too so you get what i think you were looking for
<?php
$filename = "../file/attendance_log/1414001189.txt";
$contents = file_get_contents($filename);
$contents = str_replace("\"","",$contents);
$lines = explode("\n", $contents);
date_default_timezone_set('UTC');
if (count($lines)){
$lines = array_slice($lines, 1);
foreach ($lines as $line){
$data2 = explode(",", $line);
if (count($data2) == 8){
echo $data2[0];
$time = mktime(0,0,1,$data2[1],$data2[0],$data2[2]);
echo $time . '<br>';
$user_no = $data2[3];
$item_no = $data2[4];
$quantity = $data2[5];
$waste = $data2[6];
$job_no = $data2[7];
}
}
}
?>
I had found the answer. It is because when the user save the file. It saved as Unicode UTF. It should save as Unicode UTF-8, that way there won't be any problems.

Categories