title: convert tabular data (mysql) to xml using php
body: <p>I have a My SQL database that has some tables. Now I want to extract the that data from a table and have it in XML format.</p>
  
  <pre><code>&lt;?php
      $username = "root";
      $password = "";
      $hostname = ""; 
  
      //connection to the database
      $dbhandle = mysqli_connect($hostname, $username, $password,"examples" ); 
      // Check connection
      if (mysqli_connect_errno()) {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
      } else
          echo "Connected to MySQL&lt;br&gt;";
  
      $xml          = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;"; 
      $root_element = "car"."s"; //fruits 
      $xml         .= "&lt;$root_element&gt;";
  
      //execute the SQL query and return records
      $result = mysqli_query($dbhandle,"SELECT id, name,year FROM cars");
      if (!$result) {
          printf("Error: %s\n", mysqli_error($dbhandle));
          exit();
      }
  
      if(mysqli_num_rows($result)&gt;0) {    
          while($result_array = mysqli_fetch_assoc($result)) {
              $xml .= "&lt;car&gt;";   
              //loop through each key,value pair in row    
              foreach($result_array as $key =&gt; $value) {          
                  //$key holds the table column name  
                  $xml .= "&lt;$key&gt;";          
                  //embed the SQL data in a CDATA element to avoid XML entity issues 
                  $xml .= "&lt;![CDATA[$value]]&gt;";            
                  //and close the element          
                  $xml .= "&lt;/$key&gt;";   
              }         
              $xml.="&lt;/car&gt;";    
          } 
      } 
  
      $xml .= "&lt;/$root_element&gt;";   
      //send the xml header to the browser header
      ("Content-Type:text/xml");   
      //output the XML data 
      echo $xml;
  
      //fetch tha data from the database 
      /*while ($row = mysqli_fetch_array($result)) {
          echo $row['id']." ".$row['name']." ". $row['year'];
          echo"&lt;br&gt;";
      }*/
      //close the connection
      mysqli_close($dbhandle);
  
  ?&gt;
  </code></pre>
  
  <p>however, I got the following error.</p>
  
  <pre><code>The XML page cannot be displayed  Cannot view XML input using style
  </code></pre>
  
  <p>sheet. Please correct the error and then click the Refresh button, or try again later.</p>
  
  <hr>
  
  <pre><code>Invalid at the top level of the document. Error processing resource 'http://.... my%20portable%20files/mysqlxml.php'. ... Connected to MySQL&lt;br&gt;&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;cars&gt;&lt;car&gt;&lt;id&gt;&lt;![CDATA[1]]&gt;...`
  </code></pre>
  
  <p>could you help me please.</p>