【问题标题】:Creating a simple RSS from dynamic content in PHP在 PHP 中从动态内容创建简单的 RSS
【发布时间】:2017-07-14 20:43:28
【问题描述】:

我正在使用 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>

所以我需要在我的代码中修改什么以实现我想要的上面。

【问题讨论】:

    标签: php xml rss


    【解决方案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);
    }
    

    【讨论】:

    • 感谢您的帮助。我非常感谢您的快速回复。我有一个简单的问题,如何在我的代码 $root = $doc->createElement('rss'); 中添加这个“”。就像在 xml 中一样,它只是打印
    • 你只需要$root = $doc-&gt;createElement('rss'); $root-&gt;setAttribute("version", "2.0");
    • btw 你可以将 create*() 调用嵌套到 appendChild() 中, appendChild() 将返回附加的节点。一个典型的链是:$parentNode-&gt;appendChild($document-&gt;createElement('element'))-&gt;appendChild($document-&gt;createTextNode('text content'))。这样可以避免很多变量,但要注意格式以保持可读性。
    • btw 你可以将 create*() 调用嵌套到 appendChild() 中, appendChild() 将返回附加的节点。一个典型的链是:$parentNode-&gt;appendChild($document-&gt;createElement('element'))-&gt;appendChild($document-&gt;createTextNode('text content'))。这样可以避免很多变量,但要注意格式以保持可读性。
    猜你喜欢
    • 1970-01-01
    • 2012-10-22
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多