Click to See Complete Forum and Search --> : XML Generated by PHP


Jster
03-20-2007, 09:35 AM
I'm testing to creating an xml file using php and i am running into an issue. It keeps putting a space in front of the string so it gives me an error "xml declaration not at start of external entity". any ideas as to why a space is being placed in the beginning of the string. Here is the code I am using.


<?php

header("Content-type: text/xml");

$xml_output="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$xml_output .= "<entries>\n";

for($counter = 0; $counter <10; $counter++)
{
$xml_output .= "\t<entry>\n";
$xml_output .= "\t\t<date>03/20/20" . $counter . "</date>\n";
$xml_output .= "\t\t<text>Some Text HERE " . $counter . "</text>\n";
$xml_output .= "\t</entry>\n";
}
$xml_output .= "</entries>";

echo $xml_output;
?>

jasonahoule
03-20-2007, 10:25 AM
PHP5 has built in XML handling functionality. Try something like this...

<?php
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;

$root = $doc->createElement("entries");
$doc->appendChild($root);

while($i=0; $i<10; $i++) {
$entry = $doc->createElement("entry");
$date = $doc->createElement("date");
$date->appendChild(
$doc->createTextNode("03/20/20 $i")
);
$entry->appendChild($date);

$text = $doc->createElement("text");
$text->appendChild (
$doc->createTextNode("Some text here $i");
);
$entry->appendChild($text);
$doc->appendChild($entry);
}

header("Cache-Control: no-cache, must-revalidate");
header('Content-type: text/xml');
echo $doc->saveXML();
?>


This may help http://us3.php.net/manual/en/ref.dom.php

NogDog
03-20-2007, 12:05 PM
Looks like there is a space before your opening "<?php" tag, which would cause a space to be output before anything else. However, if that's the case, then your header() command would be failing, too.

Jster
03-20-2007, 12:18 PM
NogDog you were right, there was a space in front of the <?php, i removed it and it now works. I'm very new to PHP therefore this dumb moment happened.

Thanks,
Josh