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:

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);
?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With