Importing CSV files

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
leewad
Forum Commoner
Posts: 91
Joined: Tue May 11, 2004 8:32 am

Importing CSV files

Post by leewad »

Hi

I`m trying to create a script which will import data from a CSV file, I would do it via phpmyadmin but there is no seperating lines, all the data follow on - What I need is the following converting so that after every time the data count ( field count ) gets to 31(amount of fields) then it will class it as a seperating line and start on the next line.

Hope this makes sense and hope someone can help me modify it:

Code: Select all

<?PHP

$fcontents = file ('test.csv');

for($i=0; $i<sizeof($fcontents); $i++) {
$line = trim($fcontents[$i]);
$arr = explode(",", $line);
$sql = "insert into table_test values ('".
    implode("','", $arr) ."')";

 echo $sql ."<br>\n";

}
?>
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

fgetcsv() would be much better suited to do the job.
there's a nice example on the page too

fgetcsv()
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

leewad, can you post an example of what the source file looks like?
leewad
Forum Commoner
Posts: 91
Joined: Tue May 11, 2004 8:32 am

Post by leewad »

I have sorted it now, thanks to scottayy
Post Reply