I discover the problem this is
$r .= trim($data[$i]) != ""?"\t\t<{$titles[$i]}>$data[$i]</{$titles[$i]}>\n":"";
DO I need to name r different???
Oops, sorry, forgot about that line, this should do it.
<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", true);
ini_set('memory_limit', '24M');
$file = "pets_feed_" . date("Ymd") . ".xml";// - for yyyymmdd
if (!file_exists($file)) touch($file);
$fh = fopen($file, "r");
function csv2xml($file, $container = 'data')
{
$dataarray = array();
$r = "<{$container}>\n";
$row = 0;
$cols = 0;
$titles = array();
$handle = @fopen($file, 'r');
if (!$handle) return $handle;
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
{
if (!$cols) $cols = count($data);
for ($i = 0; $i < $cols; $i++)
{
if ($row == 0)
{
$titles[$i] = $data[$i];
continue;
}
$emailsarray = array();
if(strtolower($titles[$i]) == "description")
{
foreach(explode(" ", $data[$i]) as $value)
{
if(eregi("^[a-zA-Z0-9/\._\-]+@[a-zA-Z0-9_\-]+\.[a-zA-Z0-9\._\-]+$", $value))
{
$emailsarray[] = $value;
}
}
}
$dataarray[$titles[$i]][] = trim($data[$i]) != ""?$data[$i]:"";
foreach($emailsarray as $value)
{
$dataarray["email"][] = $value;
}
}
$row++;
}
fclose($handle);
$containers = array("email");
foreach($dataarray as $key=>$value)
{
if(in_array(strtolower($key), $containers))
{
$r .= "\t\t<" . $key . "-container>\n";
}
foreach($value as $value2)
{
$tabchars = "\t\t";
if(in_array(strtolower($key), $containers))
{
$tabchars .= "\t\t";
}
$r .= $tabchars . "<$key>$value2</$key>\n";
}
if(in_array(strtolower($key), $containers))
{
$r .= "\t\t</" . $key . "-container>\n";
}
}
$r .= "</{$container}>\n";
return $r;
}
$xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n";
$xml .= csv2xml('petsfeed.csv', 'petad');
$xmlfile = @fopen('dtifeed.xml', 'wb') or die('Could not open XML file for writing');
fwrite($xmlfile, $xml) or die('Could not write string to XML file');
fclose($xmlfile);
echo "Successfully wrote the XML file";
?>
it has been changed to this line
$dataarray[$titles[$i]][] = trim($data[$i]) != ""?$data[$i]:"";
The reason I added the data to $dataarray is because it is possible now to have multiple email addresses and it is (I believe) xml compliant that when you have multiple of anything that they should go into a container. Or maybe it is just good practice.
This line here defines your containers:
$containers = array("email");
Another thing that this does is if you have an email field and you are also pulling email addresses out of the description, you want them to be grouped together, the $dataarray allows you to do that by adding all of the email address to $dataarray['email'] key and then looping through after all the data is looped through.