johnny
johnny

Reputation: 19735

How do I print out an XML response from an XML database result array in PHP?

I have a query that returns my rows as already made XML. If it matters, it is Oracle. When I run my query natively, XMLELEMENT function.

For example, from the Oracle documentation:

SELECT XMLELEMENT("Emp",
      XMLATTRIBUTES(e.employee_id AS "ID", e.last_name),
      XMLELEMENT("Dept", e.department_id),
      XMLELEMENT("Salary", e.salary)) AS "Emp Element"
   FROM employees e
   WHERE e.employee_id = 206;

Emp Element
---------------------------------------------------------------
<Emp ID="206" LAST_NAME="Gietz">
  <Dept>110</Dept>
  <Salary>8300</Salary>
</Emp>

How can I make PHP return an XML file, so I don't have to do any '<' . $row['lastname'] . '>';` type statements. I don't need anything like that because it is all handled in my query.

Whenever I use print_r() it strips all my nodes and only gives me the value in the nodes. Same with key, value in a foreach.

<Emp ID="206" LAST_NAME="Gietz">
  <Dept>110</Dept>
  <Salary>8300</Salary>
</Emp>

ends up with all the xml tags stripped,

110
8300

My code is:

$dbh = new PDO('oci:dbname=tnsname,'username','password');
                $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $stmt = $dbh->prepare($sql);
                $stmt->execute();
                $result = $stmt->fetch();
                array_shift($result);

//Create a new DOM document and load XML into its internal XML tree
$xml = new SimpleXMLElement($result[0]);

echo $xml->asXML();
print_r($result);

EDIT: Ended up with this, thanks for ThW.

header('Content-Type: application/xml; charset=utf-8');
echo '<employee>';
foreach ($result as $key=>$value)
{
    echo $result->$key;
}
echo '</employee>';

Upvotes: 0

Views: 63

Answers (1)

ThW
ThW

Reputation: 19492

Do not output a simple string with print_r(), use echo or print().

The browser does not strip your nodes, it just renders it as HTML. It ignores unknown elements and outputs the text nodes. Check the source view in the browser.

To make the browser recognize the XML, send the content type.

header('Content-Type: application/xml; charset=utf-8');
echo $result[0];

Upvotes: 1

Related Questions