Read file and store into a variable - php

<?php
$userName = array();
$tutorial = array();
$myFile = "students.txt";
$fh = fopen($myFile,'r');
while( !feof($myFile) ){
$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content
}
fclose($myFile);
echo "$userName";
echo "$tutorial";
?>
and my students.txt content
dasdsa
A
asdasd
D
How to read that and store into different array and print them out

your code should work as expected. I assume you're bit confused with echo "$userName"; output as it displays Array word. try var_dump($userName) instead

Do exactly as you've done, but change
$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content
to
$userName[] = fgets($fh);//Save first line content
$tutorial[] = fgets($fh);//Save second line content
(no need to keep the subitems in their own seperate array)
and print them out by either using print_r, or iterate through them:
for ($i = 0; $i < count($userName); $i++) {
echo $userName[$i] . " - " . $tutorial[$i];
}

$text = file_get_contents('students.txt');
$text = explode("\n",$text);
$output = array();
foreach($text as $line)
{
$output[] = $line;
}

Use function file() in PHP
file — Reads entire file into an array
$array_lines = file('students.txt');
$count = count($array_lines);
$first_arr = array();
$sec_arr = array();
foreach ($array_lines as $i => $line){
if($i%2) $first_arr[] = $line;
else $sec_arr[] = $line;
}
print_r($first_arr);
print_r($sec_arr);
With file() function every line is read as element in array. You can check it with:
print_r($first_arr);

Related

How to read a file and sum the number of that file in php

Let's say you have a file with the following structure: txt format
"id,name,value
1,Dan,150
2,Peter,300
3,Mark,400
4,Victor,600"
This function I used to read the file :
function readAFile()
{
$userfileInfo = fopen("peopleInformation.txt", "r") or die("Unable to open the file.");
//echo fread($userfileInfo, filesize("peopleInformation.txt"));
$theData = fread($userfileInfo, filesize("peopleInformation.txt"));
echo $theData;
fclose($userfileInfo);
}
Output:
"id,name,value 1,Dan,150 2,Peter,300 3,Mark,400 4,Victor,600"
How i will seperate 150, 300, 400, 600 and sum them in php.
It's a csv file, you can explode each line with , and sum the last item except the first header line.
$lines = file($file_path);
$lines = array_map(function($v){return explode(",",$v);},array_slice($lines,1));
echo array_sum(array_column($lines,2)) . PHP_EOL;
Try to use preg_match_all and RegEx
function readAFile()
{
$userfileInfo = fopen("peopleInformation.txt", "r") or die("Unable to open the file.");
//echo fread($userfileInfo, filesize("peopleInformation.txt"));
$theData = fread($userfileInfo, filesize("peopleInformation.txt"));
echo $theData;
preg_match_all('/\d+,.+,(\d+)/', $theData, $output);
$sum = 0;
foreach($output[1] as $value){
$sum = $sum + (int) $value;
};
//echo "Sum :".$sum;
fclose($userfileInfo);
}
You can use fgets function to read it line by it. Then you can easily use explode function to change the line into array. The last index in the array is your desired value.
something like below:
$theData = fopen("peopleInformation.txt", "rw");
fgets($theData); //skip the header.
$sum = 0;
while (! feof ($my_file))
{
$line = fgets($theData);
$array_val = explode($line);
$sum += (int)end($array_val);
}

read json file line by line

i want to read test.txt file line by line that i converted it to object but my problem is it just read line 1 and something is wrong because loading is little long
$file = fopen(__DIR__.'/test.txt','r');
while (!feof($file)){
$file = fgets($file);
$obj = json_decode($file);
echo $obj->sid;
echo "<hr>";
}
this my test.txt:
{"sid":5555,"trans-id":"PROV_149663920543900000801","status":"0","base-price-point":"0","msisdn":"989905978846","keyword":"sub1","validity":1}
{"sid":2244,"trans-id":"PROV_149663920543900000801","status":"0","base-price-point":"0","msisdn":"989905978846","keyword":"sub1","validity":1}
You are overwriting $file on line 3 of your code. Change it to $line and you are good to go.
$file = fopen(__DIR__.'/test.txt','r');
while (!feof($file)){
$line = fgets($file);
$obj = json_decode($line);
echo $obj->sid;
echo "<hr>";
}
Try this:
<?php
$filename= __DIR__.'/test.txt';
$array = explode("\n", file_get_contents($filename));
foreach ( $array as $line)
{
$obj = json_decode($line);
echo $obj->sid;
echo "<hr>";
}
?>
Use the file() function:
$contents = file(__DIR__.'/test.txt');
foreach ($contents as $line)
{
$obj = json_decode($line);
echo $obj->sid;
echo "<hr>";
}
The file() function read a file and create an array with each line of the file's contents.
I'd suggest using file to read the file as this generates the individual lines as array entries so you can iterate though each line using a foreach
$file=__DIR__ . '/json_src.txt';
$lines=file($file);
foreach( $lines as $line ){
$json=json_decode( $line );
printf('%s<hr />', $json->sid );
}

PHP - Searching words in a .txt file

I have just learnt some basic skill for html and php and I hope someone could help me .
I had created a html file(a.html) with a form which allow students to input their name, student id, class, and class number .
Then, I created a php file(a.php) to saved the information from a.html into the info.txt file in the following format:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
and so on (The above part have been completed with no problem) .
After that I have created another html file(b.html), which require user to enter their name and id in the form.
For example, if the user input name2 and id2 in the form, then the php file(b.php) will print the result:
Class: classB
Class Number: 24
I have no idea on how to match both name and id at the same time in the txt file and return the result in b.php
example data:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
<?php
$name2 = $_POST['name2'];
$id2 = $_POST['id2'];
$data = file_get_contents('info.txt');
if($name2!='')
$konum = strpos($data, $name2);
elseif($id2!='')
$konum = strpos($data, $id2);
if($konum!==false){
$end = strpos($data, "\n", $konum);
$start = strrpos($data, "\n", (0-$end));
$row_string = substr($data, $start, ($end - $start));
$row = explode(",",$row_string);
echo 'Class : '.$row[2].'<br />';
echo 'Number : '.$row[3].'<br />';
}
?>
Iterate through lines until you find your match. Example:
<?php
$csv=<<<CSV
John,1,A
Jane,2,B
Joe,3,C
CSV;
$data = array_map('str_getcsv', explode("\n", $csv));
$get_name = function($number, $letter) use ($data) {
foreach($data as $row)
if($row[1] == $number && $row[2] == $letter)
return $row[0];
};
echo $get_name('3', 'C');
Output:
Joe
You could use some simple regex. For example:
<?php
$search_name = (isset($_POST['name'])) ? $_POST['name'] : exit('Name input required.');
$search_id = (isset($_POST['id'])) ? $_POST['id'] : exit('ID input required.');
// First we load the data of info.txt
$data = file_get_contents('info.txt');
// Then we create a array of lines
$lines = preg_split('#\\n#', $data);
// Now we can loop the lines
foreach($lines as $line){
// Now we split the line into parts using the , seperator
$line_parts = preg_split('#\,#', $line);
// $line_parts[0] contains the name, $line_parts[1] contains the id
if($line_parts[0] == $search_name && $line_parts[1] == $search_id){
echo 'Class: '.$line_parts[2].'<br>';
echo 'Class Number: '.$line_parts[3];
// No need to execute the script any further.
break;
}
}
You can run this. I think it is what you need. Also if you use post you can change get to post.
<?php
$name = $_GET['name'];
$id = $_GET['id'];
$students = fopen('info.txt', 'r');
echo "<pre>";
// read each line of the file one by one
while( $student = fgets($students) ) {
// split the file and create an array using the ',' delimiter
$student_attrs = explode(',',$student);
// first element of the array is the user name and second the id
if($student_attrs[0]==$name && $student_attrs[1]==$id){
$result = $student_attrs;
// stop the loop when it is found
break;
}
}
fclose($students);
echo "Class: ".$result[2]."\n";
echo "Class Number: ".$result[3]."\n";
echo "</pre>";
strpos can help you find a match in your file. This script assumes you used line feed characters to separate the lines in your text file, and that each name/id pairing is unique in the file.
if ($_POST) {
$str = $_POST["name"] . "," . $_POST["id"];
$file = file_get_contents("info.txt");
$data = explode("\n", $file);
$result = array();
$length = count($data);
$i = 0;
do {
$match = strpos($data[$i], $str, 0);
if ($match === 0) {
$result = explode(",", $data[$i]);
}
} while (!$result && (++$i < $length));
if ($result) {
print "Class: " . $result[2] . "<br />" . "Class Number: " . $result[3];
} else {
print "Not found";
}
}

php data from text file to multidimensional array doesnt work but no console errors

I've written some code to read in data from a text file.
The data looks like this:
11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3
the following code reads the date, splits it one string for each line, those go in one array. This works perfectly.
After this, it should devide each line again in string that go in an array, and all these arrays go into one multidimensional array.
This last part doesnt work...
I think it's strange that instead of errors, of half the page, it shows just an empty page...
also, I've tried putting some of the code in comment, and so I've narrowed it down a bit. I give you guys the commented code, but all the comments should go away, and it should work like that!
thanks!
<?php
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
$parts = null;
fclose($fp);
print_r($lines);
echo sizeof($lines);
for ($i=0; $i < sizeof($lines)-1 ; $i++) { //the minus 1 corrects the empty line automatically added when saving the data.txt file
//$tempParts[] = explode(":", $lines[i]);
//array_push($parts, $tempParts);
}
//echo "<br/>"
echo "all parts: "
//for ($row=0; $row < sizeof($lines)-1; $row++) {
// for ($col=0; $col < sizeof($parts[$row]); $col++) {
//echo $parts[$row][$col];
// }
//}
?>
I think preg_split will do what you want.
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
//$content = "11:12:12:test titel 1
12:13:13:test titel 2
13:14:14:test titel 3";
$arr = preg_split("/(:|\n)/" ,$content);
var_dump($arr);
See here: http://www.phpliveregex.com/p/hNH
Click on preg_split on the right side of the screen to make it work
Maybe this works better for you?
preg_match_all("/(\d+):(\d+):(\d+):(.*)/", $content, $arr);
Click preg_match_all:
http://www.phpliveregex.com/p/hNW
I'm not sure to understand exactly what you want but you can try this :
if (!$fp = fopen("data.txt","r")) {
die("fail to open");
}else {
$all = array();
$row = 1;
while(!feof($fp)) { // foreach line
$ligne = fgets($fp,255); // get line content
$cols = explode(':', $line); // gets cols
$all[$row++] = $cols; // put cols on current row
}
var_dump($all); // dump all data stored by row
fclose($fp);
}

PHP Read a number from a txt file and make then calculations

I have a file which has only one line, with a number from 1 to 40, and I have the following code:
$file_line = file('../countersaver.txt');
foreach ($file_line as $line) {
$line_result = $line;
}
echo $line;
I have to calculate the result of $line - 1 and echo that result.
But when i do:
$line = $line - 1;
Then it shows $line - 1 and doesn't actually do the calculation.
Your code is weak to changes of the file contents. If someone adds a few blank lines, for example, your code won't work. Try this out instead:
$number = trim(file_get_contents('../countersaver.txt'));
echo $number - 1;
Try replacing
$line = $line - 1;
echo $line
with
$line = ($line -1);
echo $line
This will print 19 instead of 20-1.
I don't see an approved answer here but for anyone looking at this post, if you have a variable that you want PHP to read as a number you can use intval() function. Details covered here...
http://php.net/manual/en/function.intval.php
Try this:
$fin = #fopen("path to file", "r");
if ($fin) {
while (!feof($fin)) {
$buffer = fgets($fin);
}
fclose($fin);
}

Categories