Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How am i able to format XML output correctly

I'm trying to display the contents of a database in an XML format using PHP. I'm able to display the data, however I'm unable to format it correctly. Any advice would be much appreciated.

Output I am trying to achieve.

<people>
    <person>
        <id>111</id>
        <first_name>sara</first_name>
        <last_name>smith</last_name>
        <email>[email protected]</email >
    </person >
</people>

Output is currently like this:

enter image description here

My PHP code

<?php 
  // Create con
    $con=mysqli_connect("HOST","USERNAME","PASSWORD","DB");

    // Check connection
    if (mysqli_connect_errno())
    {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    //get student ID from URL
    $STU_ID = $_GET['id'];

    $sql = "SELECT * FROM table";
    $res = mysqli_query($con, $sql);

    $xml = new XMLWriter();

    $xml->openURI("php://output");
    $xml->startDocument();
    $xml->setIndent(true);

    $xml->startElement('people');

    while ($row = mysqli_fetch_assoc($res)) {
      $xml->startElement("person");

      $xml->writeElement("id", $row['id']);
      $xml->writeElement("first_name", $row['first_name']);
      $xml->writeElement("last_name", $row['last_name']);
       $xml->writeElement("email", $row['email']);
      $xml->writeRaw($row['person']);

      $xml->endElement();
    }

    $xml->endElement();

    header('Content-type: text/xml');
    $xml->flush();

     mysqli_free_result($res); 
    // Close connections
    mysqli_close($con);
?>
like image 673
Aaron Strickland Avatar asked Nov 21 '25 20:11

Aaron Strickland


1 Answers

Per the comments above...

When viewing html or xml in a browser, unknown tags inside angled-brackets are not rendered. You can view them with the browser's View Source option.

As Josh Taylor pointed out in a comment, you should be able to output

header('Content-type: text/xml');

But see this note in http://php.net/manual/en/function.header.php:

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

like image 86
Bill Karwin Avatar answered Nov 23 '25 10:11

Bill Karwin