tags:

views:

53

answers:

2

Heres a simple php script that generates some XML:

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
header("Content-Type: text/plain");

// create root element
$root = $dom->createElement("page");
$dom->appendChild($root);

// loop through all posts
while (have_posts()) : the_post();

    // create child element
    $item = $dom->createElement("title");
    $root->appendChild($item);

    // add title data
    $text = $dom->createTextNode(the_title());
    $item->appendChild($text);

endwhile;

// save and display tree
echo $dom->saveXML();
?>

It seems that using a function the_title() within my XML ends up printing outside of the xml tree (below is the browser output from the above code):

This is my second postHello world!<?xml version="1.0"?>
<page><title></title><title></title></page>

The above code seems to work fine if i replace the function the_title() with some static text, the xml is generated as required, e.g if

$text = $dom->createTextNode("Title-goes-here");

The XML generated is (which is exactly how i want it):

<?xml version="1.0"?>
<page><title>Title-goes-here</title><title>Title-goes-here</title></page>

the_title() is a Wordpress function, and i am trying to render the page in XML format.

+3  A: 

I think the functions like the_post() and the_title() will immediately output the value rather than returning it. Some of them have equivalents like get_the*() which will return the value instead of printing; this is probably what you want.

This answer might be useful

Tom Haigh
Super! I guess it would have helped if i mentioned WordPress in there somewhere. Thanks for your assistance.
mozami
+1  A: 

I would also not recommend to generate XML using DOMDocument. It is rather slow and memory-consuming. Consider using XMLWriter or "pupre-php" way.

FractalizeR
Thanks FractalizeR, appreciate the tip!
mozami