从PHP中的动态内容创建简单的RSS

时间:2017-07-14 20:43:29

标签: php xml rss

我正在使用PHP创建一个包含动态内容的简单RSS,我正在使用以下代码:

PHP代码:

$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('rss');
$root = $doc->appendChild($root);
$xml = simplexml_load_string($xml_data->asXML());
foreach($xml->data->item as $item)
{
    $title = $doc->createElement('title');
    $title = $root->appendChild($title);
    $text = $doc->createTextNode($item->title);
    $text = $title->appendChild($text);
    $link = $doc->createElement('link');
    $link = $root->appendChild($link);
    $text = $doc->createTextNode("http://example.com/xyz/?zyx=".$item->id);
    $text = $link->appendChild($text);
}
echo 'Wrote: ' . $doc->save("/directory/jobs00.xml") . ' bytes';

我在上面的代码中获得了什么结果:

<rss>
    <title>title1</title>
    <link>http://example.com/xyz/?zyx=11008</link>
    <title>title2</title>
    <link>http:/example.com/xyz/?zyx=11009</link>
</rss>

我想要的结果是什么:

<rss>
    <channel>
        <item>
            <title>title1</title>
            <link>http://example.com/xyz/?zyx=11008</link>
        </item>
        <item>
            <title>title2</title>
            <link>http://example.com/xyz/?zyx=11009</link>
        </item>
    </channel>
</rss>

所以我需要在我的代码中修改以实现我想要的内容。

1 个答案:

答案 0 :(得分:1)

你可能需要调整它的构建方式,但它只是你现有的扩展......

$xml = simplexml_load_string($xml_data->asXML());
$channel = $doc->createElement('channel');
$root->appendChild($channel);
foreach($xml->data->item as $item)
{
    $title = $doc->createElement('title');
    $text = $doc->createTextNode($item->title);
    $text = $title->appendChild($text);
    $link = $doc->createElement('link');
    $text = $doc->createTextNode("http://example.com/xyz/?zyx=".$item->id);
    $text = $link->appendChild($text);
    $item = $doc->createElement('item');
    $item->appendChild($title);
    $item->appendChild($link);
    $channel->appendChild($item);
}