1

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'
];
1
  • 1
    Look into file() (if your file isn't too big). Commented Sep 6, 2020 at 13:44

3 Answers 3

1

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

file() would be basically doing the same as file_get_contents() + manual line splitting.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.