read json file line by line - php

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 );
}

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 Files from directory and echo certain line

I want to read all files from a directory but instead of displaying the first character i want to display a certain line, f.e. line 4.
<?php
$directory = "content/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode("|", $contents);
foreach ($items as $item) {
echo "$item[0]";
}
}
}
closedir($dir);
?>
Thanks!
You can use file() function. It reads files into an array, where every line will be an array member, to skip empty lines pass the FILE_SKIP_EMPTY_LINES flag paramater.
For more info consult the docs.
// `$items` is already an array
$items = explode("|", $contents);
// if you want first element of array just:
echo $item[0];
// if you want fourth element of array just:
echo $item[3];
// without `foreach`
Could you show your file structure, please?
Basicaly you can use something like this:
$contents = file_get_contents($filename);
$items = explode("\r\n", $contents); //explode file content
foreach ($items as $item) {
echo $item[3]; //echo your line
}

How can i show all lines of a text document except a specific line in PHP?

$file=fopen("question.txt","r");
while(!feof($file))
{
echo "<h3>". fgets($file)."</h3>"."<br />";
for($i=0;$i<=3;$i++)
{
echo fgets($file)."<br />";
}
}
$lines =file("filename.txt");
and then $lines[4] will return you fifth line.
Find and replace the line. Look at str_replace function at http://php.net/manual/en/function.str-replace.php :)
Maybe a better option in this case... Use the file($path) function to get the lines into an array, then loop through it.
$lines = file($path, FILE_IGNORE_NEW_LINES);
$remove = "balblalbllablab";
foreach($lines as $key => $line)
if(stristr($line, $remove)) unset($lines[$key]);
$data = implode('\n', array_values($lines));
$file = fopen($path);
fwrite($file, $data);
fclose($file);

Read file and store into a variable

<?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);

In PHP how to sort a file in reverse?

i have a text (text.txt) file like this:
shir
beer
geer
deer
i have also a php page with that source:
<?php
foreach (glob("*.txt") as $filename) {
$file = $filename;
$contents = file($file);
$reverse = array_reverse($file, true);
$string = implode("<br>" , $contents);
echo $string;
echo "<br></br>";
}
?>
I want that in the php page it will show:
deer
geer
beer
shir
from the end of the file to the beginning.
thank you
Looks like you are reversing the file name and not the contents.
Do
$reverse = array_reverse($content); // you can drop 2nd arg.
$string = implode("<br>" , $reverse);
in place of
$reverse = array_reverse($file, true);
$string = implode("<br>" , $contents);
Also you can remove the temp variables from you script and do:
foreach (glob("*.txt") as $filename) {
echo implode("<br>" , array_reverse(file($filename))) . "<br></br>";
}
<?php
foreach (glob("*.txt") as $filename) {
$file = $filename;
$contents = file($file);
$reverse = array_reverse($contents, true);
$string = implode("<br>" , $reverse);
echo $string;
echo "<br></br>";
}
?>
Your result was a $contents, without reverse.

Categories