xml parsing script
Posted: Tue Sep 16, 2003 2:44 pm
parsing xml feed into mysql --
greets, I am looking for ideas on a more efficient way to handle this. Worked with line by line parsing but that wasn't as consistent with start and end tags. I ended up writing it like this, but I prefer to stay away from dumping files to strings..
thanks!
greets, I am looking for ideas on a more efficient way to handle this. Worked with line by line parsing but that wasn't as consistent with start and end tags. I ended up writing it like this, but I prefer to stay away from dumping files to strings..
thanks!
Code: Select all
<?php
// dbFieldname => tagname
$tagstofind = array("headline" => "hl1",
"source" => "distributor",
"entrydate" => "dateline",
"location" => "location",
"body" => "body.content");
$newsdirectory="./xmlsource/";
if(!($files = opendir("$newsdirectory"))) {
print("directory could not be opened.");
exit;
}
while($filename = readdir($files)) {
if(stristr($filename, ".xml")){
if(!($filedata=file($newsdirectory.$filename))){
print"couldn't open the file.<p>";
}
else {
$filestring=implode($filedata,"");
foreach ($tagstofind as $field => $tagname) {
$tmpstring = "dummytoken".$filestring;
$tmpstring = str_replace("<{$tagname}>", "‡‡", $tmpstring);
$tmpstring = str_replace("</{$tagname}>", "‡‡", $tmpstring);
$token = strtok($tmpstring, "‡‡");
$token = strtok("‡‡");
if($token != ""){
$found[$field].= $token;
}
unset($token);
unset($tmpstring);
}
$count=count($found);
$a=0;
foreach ($found as $fieldname => $value) {
$value=trim($value);
$insertfields.=$fieldname;
$insertvals.="'".addslashes($value)."'";
if($a < ($count-1)){
$insertfields.=",";
$insertvals.=",";
$a++;
}
#print "$fieldname: $value<hr>";
}
$query = "INSERT INTO feed (".$insertfields.") VALUES (".$insertvals.")";
echo $query;
}
}
}
?>