开发者

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

开发者 https://www.devze.com 2022-12-10 04:42 出处:网络
Heres a simple php script that generates some XML: <?php // create doctype $dom = new DOMDocument(\"1.0\");

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消