My API processor returns data in one of several formats designated by the "type' keyword in the request. I am able to invoke, for instance, a JSON header using the following method, but this does not work for XML. Is there a way of invoking this without producing an error?
<?PHP
if($_REQUEST['type'] == "XML")
{
header ("Content-Type:text/xml");
}
There is no white space in the header designation. Later down the line, I am using PHP's dom class to formulate the XML. This looks like this
$dom = new DOMDocument("1.0", 'utf-8');
$root = $dom->createElement("Data");
$dom->appendChild($root);
if(!empty($Error))
{
$Er = $dom->createElement("Errors");
$root->appendChild($Er);
foreach($Error as $value)
{
$key = "Error";
$Child = $dom->createElement($key);
$Child = $Er->appendChild($Child);
$data = $dom->createTextNode($value);
$data = $Child->appendChild($data);
}
}
else
{
foreach($XMLItems as $key => $value)
{
$key = $dom->createElement($key);
$root->appendChild($key);
$variable = $dom->createTextNode($value);
$key->appendChild($variable);
}
}
$dom->preserveWhiteSpace = FALSE;
$dom->formatOutput = TRUE;
echo $dom->saveXML();
Solution: What I did to solve the problem here, following aynber's suggestions, is to eliminate any blank lines in the PHP as well as and any includes. I eliminated closing PHP tags and extra lines in those includes as well as the main file. This eliminated the two blank lines at the top of the file, allowing me to insert the XML header.
CodePudding user response:
"XML Parsing Error: XML or text declaration not at start of entity"
means that somewhere at the start of your XML output, there is a space or other character that's not supposed to be there. There are a few places to check:
- The beginning of every PHP file. Make sure there are no spaces, new lines, or invisible characters before
<?php
- Any place you break out of and back into the PHP blocks. Anything there will be sent to the browser, even if it is white space.