Hi, I have data in a txt file which i want to import into a sql database. The txt file looks like this: email@website.co.uk|Joe|Bloggs|000 000 000 Code (markup): I am using the following code to import with no luck. $file = "textfile.txt"; $fp = fopen($file, "r"); $data = fread($fp, filesize($file)); fclose($fp); $output = explode("|", $output); foreach($output as $var) { $tmp = explode("|", $var); $email_address = $tmp[0]; $name = $tmp[1]; $surname = $tmp[2]; $telephone_number = $tmp[3]; mysql_query("INSERT INTO `table` (email_address, name, surname, telephone_number) VALUES ('" . $email_address . "', '" . $name . "', '" . $surname . "', '" . $telephone_number . "')") or trigger_error(mysql_error(),E_USER_ERROR); } PHP: Any ideas why this is not importing? Cheers, Adam
youre trying to call variables from a .txt file. you have to call it as text .. and then import it into your PHP file and give the data (per line) a variable. so do your fread and open the text file etc .. then import it line by line. and each line canm be given a variable of like $email_1 etc But if youre looking for specific data in a .txt file, then you have to find it then call everything on that text line. It really depends how you have it set up. But if youre calling a .txt file and reading it .. its not going to make it a variable in PHP ..its only text. I did somethin like this before where the information was saved on its own line with /n new line break . then call it line by line and have eachline given a variable putput into PHP. you'll have to do a special fread that reads text line by line. and putput each line into PHP so that it makes whatever is on that line of text into like $var1 = "(text from that line)"; $var2 = "(text from 2nd line)"; etc. because you can have fread pull it line by line and you can give it its own variable $var_line1, $var_line2 etc
The line breaks are preventing your script from working properly. Try something like this instead: $lines = file('textfile.txt'); foreach ($lines as $line_num => $line) { $output = explode("|", $line); //TRY THE REST OF YOUR SCRIPT STARTING HERE... } PHP:
This code will work: <?php $file = "textfile.txt"; $fp = fopen($file, "r"); $data = fread($fp, filesize($file)); fclose($fp); $output = explode("\n", $data); foreach ($output as $key => $value) { $result = explode("|",$value); $email_address = $result[0]; $name = $result[1]; $surname = $result[2]; $telephone_number = $result[3]; mysql_query("INSERT INTO `table` (email_address, name, surname, telephone_number) VALUES ('" . $email_address . "', '" . $name . "', '" . $surname . "', '" . $telephone_number . "')") or trigger_error(mysql_error(),E_USER_ERROR); } ?> PHP: