简体   繁体   中英

Generating XML from PHP functions (what am i doing wrong?)

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, eg 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM