Outputting XML string from MySQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
chenzen
Forum Newbie
Posts: 2
Joined: Wed May 20, 2009 7:38 am

Outputting XML string from MySQL

Post 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>";
    }
}
?>
 
Last edited by Benjamin on Wed May 20, 2009 8:07 am, edited 1 time in total.
Reason: Changed code type from text to php.
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Outputting XML string from MySQL

Post 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...
chenzen
Forum Newbie
Posts: 2
Joined: Wed May 20, 2009 7:38 am

Re: Outputting XML string from MySQL

Post 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.
Post Reply