sitehatchery
08-12-2006, 01:00 AM
I've stored the contents of a file into a variable.
The file is composed of words and definitions - as such:
[Direct Imaging]Imaging that by-passes the need for film such as imaging from original copy direct to plate or electronic imaging from digital data directly to a proof or printing plate.
[Direct-To-Plate Technology] Those imaging systems that receive fully paginated materials electronically from computers and expose this information to plates in platesetters or imagesetters without creating film intermediates. Also called CTP or Computer-to-plate.
...
What I need to do is grab words and their definitions and write them to a database.
What should I do?
NogDog
08-12-2006, 01:12 AM
$values = '';
foreach($arrayName as $word => $definition)
{
$values = ($value != '') ? ", ('$word', '$definition')" : "('$word', '$definition')";
}
if($values != '');
{
$query = "INSERT INTO `table_name` (`word`, `definition`) VALUES $values";
// execute query here using applicable function for your database type
}
else
{
// report error that nothing was found to insert
}
sitehatchery
08-12-2006, 02:44 AM
This was a one time deal. I had thousands of words and definitions that I had to extract from a text file and insert into a database. Somehow we web developers end up at one time or another spending our time (and the clients money) doing data entry. So, I've finally come up with a way to extract words and definitions and feed them into a database. I thought it would be good to share it with y'all:
I borrowed a lot of the code from an entry on http://us3.php.net/strpos and modified it to fit my need. Thanks NogDog for giving helping me get the array values into the database.
function file_segments($haystack, $needle_start, $needle_end) {
$array = array();
while(($pos_start = strpos($haystack,$needle_start,$pos_start)) !== false) {
$pos_end = strpos($haystack,$needle_end,$pos_start);
$word = substr($haystack,$pos_start + strlen($needle_start),$pos_end - $pos_start - strlen($needle_start));
$definition=substr($haystack,$pos_end + strlen($needle_end));
$definition=substr($definition, 0, strpos($definition, $needle_start));
$post_start++;
$array[$word]=$definition;
}
return $array;
}
$handle = fopen("definitions.txt", "r");
$contents = fread($handle, filesize('definitions.txt'));
$contArray=file_segments($contents, '[', ']');
fclose($handle);
$values = '';
foreach($contArray as $word => $definition)
{
$query = "INSERT INTO faq_terms VALUES(NULL, 2,'$word', '$definition')";
mysql_query($query);
if(mysql_error()) echo mysql_error();
}
Took a while to come up with, but it worked like a charm. Definitely more interesting than entering all that in by hand!