views:

119

answers:

2

I have a text file like....

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

I want to convert it to CSV with the help of a little bit PHP, and I want to know also how it can be reversed...ie from CSV to an ordered, or un-ordered list.....kindly help me please :)

+1  A: 
<?php
//read file
$content = file_get_content($filteredFilePath);

//explode contents into array
//if you use windows or mac, newlines may be different
//i.e: \r, \r\n
$list = explode("\n\n", $content); 

//iterate over the items and print a HTML list
//to generate ordered list, use: <ol>
echo '<ul>';
foreach($list as $item) {
    echo '<li>' . $item . '</li>';
}
echo '</ul>';

Edit: I made some modification to work with double newlines.

erenon
I have a file named data.txt and this php script file...in the same dir....and am using $fileContents = file("data.txt"); in place of your 3rd line...as I am guessing i have to provide the external file path somewhere.... :) ....and I thought that will work...but due to my absolute beginning phase, I cudnt be able to find why it is not working....what it is showing is just a single bullet...or in ordered list case, just "1."..... :S
Jumani
What kind of OS do you use?
erenon
Windows 7, 32 bit. and using Google Chrome...
Jumani
Ok, check the edited one.
erenon
Cool!...apart from ghostdog74 script, this one is working too!
Jumani
+2  A: 

To convert to CSV

$data=file_get_contents("file");
$data =explode("\n\n",$data);
echo implode(",",array_filter($data));

Update as required to convert from CSV,

$data = explode(",", file_get_contents("file") );
echo implode("\n\n",$data);

For many rows of csv data, you can iterate the file using fgetcsv(). eg

if (($handle = fopen("file.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 2048, ",")) !== FALSE) {
        $num = count($data);
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
ghostdog74
hey...you are the man!....this does the exact trick of converting list to CSV...thanks!it would be extra good...if you can tell the reverse as well.. :)
Jumani
$data = file_get_contents("csv"); $data = explode(",",$data); echo implode("\n\n",$data); is the exact inverse :P
svens
now everything is fine...except one...that the out put from CSV to list is as :"[email protected] [email protected] [email protected] [email protected]@[email protected]"....when it shud be like"[email protected]@[email protected]"i know it is the easy one to solve...just cant get through it...admitting being a n00b in PHP... :/
Jumani
so you only want unique emails list? then you have to write extra code to do that. Maybe try using array_unique(). Always refer to the docs.
ghostdog74