Page 1 of 1

Outputting XML string from MySQL

Posted: Wed May 20, 2009 7:58 am
by chenzen
Well,
I am outputting xml string after fetching records from mysql database using php. I need to parse the xml code with Javascript (the xml string is returned by an ajax function). Javascript cannot parse the string while I can use the direct output given by the php code for parsing by the Javascript code! More funny thing is that when I echo any xml string outside of a isset() or foreach() (so on ...) function, the string returned by the php code is directly usable by the javascript function, else nothing echoed by any code inside if(), foreach() works!!! Anything to do with mysql text encoding?
And I thought I have a good knowledge in PHP!!!

Code: Select all

 
 <?php
//i don't need the xml mime info here since my javascript function works with or without it
//xml string echoed from here works perfectly
 
if(isset($_GET["some_id"]) && $_GET["some_id"] > 0)
{
 
 
    ..........
    ..........
 
    if(is_array($my_array)) //$my_array is the array containing the db records
    {
         echo "<root>"; //say root is my root tag
         foreach($my_array as $value)
         {
                echo "<innode>". $value . "</innode>"; //say innode is my inner node
          }      
          echo "</root>";
    }
}
?>
 

Re: Outputting XML string from MySQL

Posted: Wed May 20, 2009 3:28 pm
by Darhazer
Open this script directly in a browse (or using the FireBug extension copy the response from the AJAX) and see if the XML is well-formated

Also, you have to escape the output, otherwise you can break the XML:

Code: Select all

 
 foreach($my_array as $value)
         {
                echo "<innode>". htmlspecialchars($value) . "</innode>"; //say innode is my inner node
          }      
 
Finally, use header('Content-type: text/xml;charset=utf-8'); before outputing...

Re: Outputting XML string from MySQL

Posted: Wed May 20, 2009 11:11 pm
by chenzen
I have checked by opening the script directly, and the output is a perfect xml string which can be directly fed to the javascript parser. only problem comes when i fetch the script content from javascript with ajax.