Skip to content Skip to sidebar Skip to footer

Invalid Xml Format - How To Avoid This

I'm getting data from a database in PHP/mysql, which has invalid characters, such as &. I'm creating the XML as follows: $stmt->bind_result($foo)|| fail('An error occurred:

Solution 1:

You could use an XMLWriter to ensure correct encoding and such.

<?php$stmt = new Dummy;
$stmt->bind_result($foo);

$xml = new XMLWriter(); 
$xml->openURI('php://output'); 
$xml->setIndent(true);
$xml->startDocument(); 

$xml->startElement("xml"); 
while ( $stmt->fetch() ) {
    $xml->startElement("RECORD");
    $xml->writeElement('FOO', $foo);
    $xml->endElement(); // RECORD
}
$xml->endElement(); // xmlclassDummy{
    publicfunctionbind_result(&$var) {
        $this->var = &$var;
    }

    publicfunctionfetch() {
        static$arr = array('Barnes & Noble', 'Barnum & Bailey', "Buy'n'Large");
        if ( current($arr) ) {
            $this->var = current($arr);
            next($arr);
            returntrue;
        }
        returnfalse;
    }
}

Solution 2:

The characters you're getting from the database are not invalid. <, >, & and such are perfectly legal text and can be included in an XML document. However because they have special meaning to an XML parser they need to be escaped. That is:

  • & --> &amp;
  • > --> &gt;
  • < --> &lt;

By far the easiest way to do this is not to build the XML by string concatenation as your code sample attempts to do. Instead use a library that automatically escapes characters as necessary as the document is constructed. XMLWriter has already been suggested. DOM is another option.

Solution 3:

I got rid of the parse error by adding a header:

header('Content-type: text/xml');
$xml = new XMLWriter('UTF-8', '1.0'); 
$xml->openURI('php://output'); 
$xml->setIndent(true);
$xml->startDocument(); 

$xml->startElement("XML"); 
while ( $stmt->fetch() ) {
    $xml->startElement("ITEM");
    $xml->writeElement('ELEMENT', $reviewdate);
    $xml->endElement(); // </ITEM>
}
$stmt->close();
$xml->endElement(); // xml$xml->flush();

unset($xml); 

Solution 4:

I would start by looking in the browsers network traffic and analyzing the xhr response body to see what your browser is getting as far as the xml payload (data). You can do this in Chrome or IE using F12 developer tools, or if you want to catch it using another proxy, take a look at Fiddler:

http://www.telerik.com/fiddler

Hope this helps!

Post a Comment for "Invalid Xml Format - How To Avoid This"