Reputation: 13
I have a file that contains certain data in Name|Address|Email|Phone
format. Each line contains the data in the said format for each customer. How do I implode or str_replace to get the format below?
Name: <br>
Address: <br>
Email: <br>
Phone: <br>
I have the idea and thought mapped out but I can't seem to be able to implement it.
N:B - Name|Address|Email|Phone
is the format not the data in itself. The data would look something like Foo Bar|123, Foo Lane|[email protected]|123-456-7890
Upvotes: 0
Views: 30
Reputation: 7485
Just use str_getcsv and swap your delimiter for the pipe.
The first part can be swapped out. Just iterate a line/row at a time.
<?php
function get_line() {
$data =<<<DATA
Holmes|Baker Street|[email protected]|01234 56789
Mouse|Baker Street|[email protected]|01234 67890
DATA;
foreach(explode("\n", $data) as $line)
yield $line;
}
foreach(get_line() as $line) {
list($name, $address, $email, $phone) = str_getcsv($line, '|');
echo 'Name: ' . $name . '<br />';
echo 'Address: ' . $address . '<br />';
echo 'Email: ' . $email . '<br />';
echo 'Phone: ' . $phone . '<br />';
}
Output:
Name: Holmes<br />Address: Baker Street<br />Email: [email protected]<br />Phone: 01234 56789<br />Name: Mouse<br />Address: Baker Street<br />Email: [email protected]<br />Phone: 01234 67890<br />
Upvotes: 0
Reputation: 54831
I presume something like this should help:
$data = explode('|', 'Foo Bar|123, Foo Lane|[email protected]|123-456-7890');
$keys = ['Name', 'Address' ,'Email', 'Phone'];
$result = [];
foreach ($data as $k => $v) {
$result[] = $keys[$k] . ': ' . $v;
}
echo implode('<br />', $result);
Fiddle here.
Upvotes: 1
Reputation: 6388
You can use
$lineBreak = "<br/>";
while ($line = fgets($fh)) {
echo $line = str_replace('|', ":".$lineBreak, $line);
}
Upvotes: 0