Reputation: 651
I am new to PHP so this may be a simple fix.
I have a text file named textt.txt
that looks like this:
South East asia,2222,code1
winter break,3333,code2
My PHP code looks like this:
<?php
$x = file_get_contents('textt.txt');
$y = explode("\r\n", $x);
$z = $y[0];
echo $z;
?>
The outcome of this is:
South East asia,2222,code1
I would like it to return only:
South East Asia.
How can I make this happen?
Upvotes: 0
Views: 1029
Reputation: 67715
Depending on your use case, you may not want to read the entire file in one shot:
$fp = fopen('textt.txt', 'r');
list($z) = fgetcsv($fp);
Upvotes: 0
Reputation: 872
I think what you want to do is to split it on \r\n like you do, and then loop trough the array and explode it on comma to only get the region:
<?php
$file = file_get_contents('textt.txt');
$fileArray = explode("\r\n", $file);
foreach($fileArray as $value) {
$region = explode(",", $value);
echo $region[0] . "<br />\n";
}
?>
Upvotes: 1
Reputation: 16933
South East asia,
2222,code1
winter break,
3333,
code2
$x = file_get_contents('textt.txt');
list($z) = explode(",", $x);
echo $z;
Upvotes: 0
Reputation: 23061
Quick & dirty:
<?php
$all_file = file_get_contents('textt.txt');
$lines = explode("\r\n", $all_file);
$first_line = $lines[0];
$items = explode(",", $first_line);
echo $item[0];
Upvotes: 0
Reputation: 270637
explode()
again on the comma. Your first call to explode()
splits the string by lines, each containing a comma-separated string.
<?php
$x = file_get_contents('textt.txt');
$y = explode("\r\n", $x);
// $y[0] now contains the first line "South East asia,2222,code1"
// explode() that on ","
$parts = explode(",", $y[0]);
// And retrieve the first array element
$z = $parts[0];
echo $z;
?>
Upvotes: 2