how to create array inside array from text file in php - php

first, i have a text file
Samsung|us|new
iPhone|china|new
i want to convert the text file, and the result must be like this
[
[
'Samsung', 'us', 'new'
],
[
'iPhone', 'china', 'new'
]
]
i have already try this, but the code only return one array
code:
<?php
$a = file_get_contents("text.txt");
$b = explode('|', $a);
result:
[
'Samsung','us','new','iPhone','china','new'
];

According to the hint from Jeto I would do the following:
at first read the file with function file() with the flag FILE_IGNORE_NEW_LINES. This reads the file line by line and creates an array.
next step would be to iterate over each element and split by | character with explode().
This could be the resulting code:
$file = file('test.txt', FILE_IGNORE_NEW_LINES);
for($i = 0; $i < count($file); $i++)
{
$file[$i] = explode('|', $file[$i]);
}

This is because file_get_contents() reads the whole file including the line breaks.
You have to first explode() on \n. After that explode() on |.
Or with array_map() in one line:
$a = file_get_contents("text.txt");
$b = array_map(fn($line) => explode('|', $line), explode("\n", $a));
// $a with \n
// this explode splits the lines
// this explodes at the | character
Example: https://3v4l.org/24qla
If you want to read some big files you can use something like this:
function getCsvData($file, $delimiter = '|') {
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
yield $data;
}
fclose($handle);
}
}
foreach(getCsvData('test.txt') as $row) {
print_r($row);
}

Don't use file_get_contents open the file and read the file line by line. Then split the line.
https://www.php.net/manual/en/function.fgets.php
Here are some example to do this. You can use fgets for this. With file_get_contents you get the whole file.
Another solution is to explode by \r\n or \n the characters for new line. Then you have the single lines and you can split them by your delimiter. But in this case you write the whole content in an array what can cause some memory problem.
explode("\n",$homepage)

Related

Php - Reading file lines into an array

The numbers in my file are 5X5:
13456
23789
14789
09678
45678
I'm trying to put it into this form
array[0]{13456}
array[1]{23789}
array[2]{14789}
array[3]{09678}
array[4]{45678}
My code is:
$fileName = $_FILES['file']['tmp_name'];
//Throw an error message if the file could not be open
$file = fopen($fileName,"r") or exit("Unable to open file!");
while ($line = fgets($file)) {
$digits .= trim($line);
$members = explode("\n", str_replace(array("\r\n","\n\r","\r"),"\n",$digits));
echo $members;
The output I'm getting is this:
ArrayArrayArrayArrayArray
fgets gets a line from the file pointer, so theoretically there should be no "\r" or "\n" characters in $line. explode will still work, even if the delimiter is not found. You'll just end up with an array with one item, the entire string. You can't echo an array, though. (That's why you're seeing Array for each line; it's the best PHP can do when you use echo on an array.)
If I were you, I would rather just use file() instead.
$members = array_map('trim', file($fileName, FILE_IGNORE_NEW_LINES));
With the example file you showed, this should result in
$members = ['13456', '23789', '14789', '09678', '45678'];
You can simply put the lines into an array and use print_r instead of echo to print that array
while ($line = fgets($file)) {
$members[] = $line;
}
print_r($members);
It should depend on the file that you are dealing with.
FileType:
text -> fgets($file)
CSV -> fgetcsv($file)

How to extract specific text from a text file in php?

i am having difficulties with extracting specific text from a text file. I have tried many different ways like using fopen or file to open the file but this wont allow me to use any of the string functions. So i have decided to use file_get_contents and extract the text i want with the string methods as follows:
<?php
$data = [];
$file =
file_get_contents("data.txt", 0, NULL, 148);
list($id, $data_names) = preg_split('[:]', $file);
array_push($names, $data_names);
echo $emails[0];
?>
I used preg_split to split the text i want at a specific character (:) and i put the data in an array. Which worked for the first line but i don't know how to go about doing it for the rest of the lines, i've tried a while loop but that just ends up in an infinite loop.
data.txt formatted like this:
1:hannah.Smith
2:Bob.jones
3:harry.white
....
Any suggestions on how to do this or a better approach would be greatly appreciated.
There is a function for that. This isn't CSV but change the delimiter. To just get the names:
$handle = fopen("data.txt", "r"));
while(($line = fgetcsv($handle, 0, ":")) !== FALSE) {
$names[] = $line[1];
}
To index the names by the ids:
while(($line = fgetcsv($handle, 0, ":")) !== FALSE) {
$names[$line[0]] = $line[1];
}
To get the ids and names in a multidimensional array, use:
while(($names[] = fgetcsv($handle, 0, ":")) !== FALSE) {}
Well you are not assigning the return value of file_get_contents to a variable. So the contents of the file are not being used.
You can use the file function. It reads the contents of a file to an array. Each element of the array is a line in the file. You can then loop over the array and parse each line. For example:
$names = array();
$file = file_get_contents("data.txt");
for ($count = 0; $count < count($file); $count++) {
list($id, $name) = $file[$count];
$names[] = $name;
}
/** print the contents of the names array */
print_R($names);

Splitting txt file delimited by tabs into multidimensional associative array

I currently am trying to read an input file that looks like this:
annie Tuesday October 7 at 08:32 pm 1 Cappuccino 2.5
It is delimited by tabs. I am trying to read from this file, called orders.txt, and place this is an associative array $array. This is the code I have so far. I have tried several different versions, but no dice.
function read_file() {
$file = "orders.txt";
$array = array();
if(file_exists($file)) {
$myfile = fopen($file, "r");
$data = file_get_contents($file);
$lines = explode("\n", $data);
foreach($lines as $line) {
$splode = explode("\t", $line);
$array[] = array(
"Name" => $splode[0],
"Time" => $splode[1],
"Quant" => $splode[2],
"Type" => $splode[3],
"Price" => $splode[4],
);
}
fclose($myfile);
}
return $array;
}
Could anyone see what I am doing wrong here? Thank you.
Your code looks good. I did add one if statement to make sure splode was 5 long before assigning it. This is protection against a possible blank line at the end of a file.
I ran it on a test file here with a few lines and it processed correctly and outputted as expected.
Depending on how you're creating this file - could you have a '\r' or a '\r\n' on the end of each line instead of just a \n?? This is something you'd need to check - maybe a hex editor, but I still think your code should run ok (unless it's just a \r) as long as there's enough tabs to satisfy the 5 on each line (which I conditionaled for in my suggestion).
function read_file()
{
$file = "orders.txt";
$array = array();
if (file_exists($file)) {
echo "Get";
$myfile = fopen($file, "r");
$data = file_get_contents($file);
$lines = explode("\n", $data);
var_dump($lines);
foreach ($lines as $line) {
$splode = explode("\t", $line);
if (sizeof($splode) >= 5) $array[] = array(
"Name" => $splode[0],
"Time" => $splode[1],
"Quant" => $splode[2],
"Type" => $splode[3],
"Price" => $splode[4],
);
}
fclose($myfile);
}
return $array;
}

fgetcsv skip blank lines in file

I have this script that I did, it basically grabs all the files in my "logs" folder and merge them all in one array file, my only problem is that, sometimes the script breaks if there is blank line or empty line! how can I tell it to automatically skip blank empty lines and go to next? blank lines are not necessarily at the top or bottom! could be in the middle of the csv file
<?php
$csv = array();
$files = glob('../logs/*.*');
$out = fopen("newfile.txt", "w");
foreach($files as $file){
$in = fopen($file, "r");
while (($result = fgetcsv($in)) !== false)
{
$csv[] = $result;
}
fclose($in);
fclose($out);
}
print json_encode(array('aaData' => $csv ));
?>
As you can read in the documentation for fgetcsv():
A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.
Checking for that before adding it to your data array should be sufficient:
while (($result = fgetcsv($in)) !== false) {
if (array(null) !== $result) { // ignore blank lines
$csv[] = $result;
}
}
This works 100% tested, simplest way. The explanation is that blank lines make fgetcsv return a non-empty array with just a null element inside.
if ($result[0] == NULL)
continue;
In short
$csv = array_map('str_getcsv', file($file_path, FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES));
Explanation
file reads the content of the file into an array. The FILE_SKIP_EMPTY_LINES will skip the empty lines in the file.
array_map will apply the function str_getcsv on each element of the array. str_getcsv will parse the string input for fields in
csv format and return an array containing the fields.
Read more about str_getcsv
Read more about file
Read more about array_map

Reading text after a certain character in php

Okay so I have a text file and inside of the text file I have these lines:
IP = 127.0.0.1
EXE = Client.exe
PORT = 8080
TITLE = Title
MAINT = False
MAINT-Message = This is the message.
what I am wanted to do is get the 'False' part on the fifth line.
I have the basic concept but I can't seem to make it work. This is what I have tried:
<?php
$file = file_get_contents('LauncherInfo.txt');
$info = explode(' = ', $file);
echo $info[5];
?>
And with this I get a result but when I echo $info[5] it gives me 'False Maint-Message' so it splits it but it only splits at the = sign. I want to be able to make it split at the where I have pressed enter to go onto the next line. Is this possible and how can I do it?
I was thinking it would work if I make it explode on line one and then do the same for the second line with a loop until it came to the end of the file? I don't know how to do this though.
Thanks.
I think you're looking for the file(), which splits a file's contents into an array of the file's lines.
Try this:
$file = file('LauncherInfo.txt');
foreach ($file as $line) {
if ($line) {
$splitLine = explode(' = ',$line);
$data[$splitLine[0]] = $splitLine[1];
}
}
echo $data['MAINT'];
Just in case you were curious, since I wasn't aware of the file() function. You could do it manually like this
<?php
$file = file_get_contents('LauncherInfo.txt');
$lines = explode("\n", $file);
$info=array();
foreach($lines as $line){
$split=explode(' = ',$line);
$info[]=$splitline[1];
}
echo $info[5];//prints False
?>

Categories