【问题标题】:How to get first <p> from each of <description> in an XML file?如何从 XML 文件中的每个 <description> 中获取第一个 <p>?
【发布时间】:2015-12-07 23:46:03
【问题描述】:

我正在解析 RSS 提要以获取原始数据并对其进行操作。

在 WordPress RSS 提要上。我可以通过遍历SimpleXMLElement 找到帖子的标题链接描述和发布。节点位于:

$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$description = $xml->channel->item[$i]->description;
$pubDate = $xml->channel->item[$i]->pubDate;

分别。

问题是 $description 里面有 2 个 &lt;p&gt;s。一个对我没用的;第二个。

那么如何将$description 分配给描述的第一个&lt;p&gt;

简单的$xml-&gt;channel-&gt;item[$i]-&gt;description-&gt;p[0] 是行不通的。它会导致内部服务器错误。

我的整个代码如下所示:

<?php 
$html = "";
$url = "http://sntsh.com/posts/feed/";
$xml = simplexml_load_file($url);

for($i = 0; $i < 10; $i++){
    $title = $xml->channel->item[$i]->title;
    $link = $xml->channel->item[$i]->link;
    $description = $xml->channel->item[$i]->description->children();
    $pubDate = $xml->channel->item[$i]->pubDate;

    $html .= "<a href='$link'><h3>$title</h3></a>";
    $html .= "$description";
    $html .= "<br />$pubDate";
}
echo $html;

【问题讨论】:

  • 您是否尝试过使用description-&gt;children() 将孩子作为数组获取? php.net/manual/en/simplexmlelement.children.php
  • 我读对了吗,您将 RSS 提要中的描述设置为变量(例如$desc = $xml-&gt;channel-&gt;item[$i]-&gt;description)。现在,您需要获取该描述的子字符串吗? (具体是第二组&lt;p&gt;标签的内容)
  • 是的!我将用修改后的子字符串替换描述。

标签: php xml wordpress rss


【解决方案1】:

您可以使用children() 方法获取元素的子元素。如果你能保证第一个子元素永远是你需要的元素,你可以这样使用它:

$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$description = $xml->channel->item[$i]->description->children();
$pubDate = $xml->channel->item[$i]->pubDate;

children() 函数旨在以迭代方式使用,每次调用它时,它都会以SimpleXMLElement 的形式返回下一个子级。 http://php.net/manual/en/simplexmlelement.children.php

编辑
问题的原因似乎是&lt;![CDATA[ ]]&gt; 标签。它们导致 SimpleXMLElement 为空。剥离它们可以修复它:

$html = '';
$src = file_get_contents('http://sntsh.com/posts/feed/');
$search = ["<![CDATA[","]]>"];
$replace = array('','');
$data = str_replace($search,$replace,$src);
$xml = simplexml_load_string($data);

for($i = 0; $i < count($xml->channel->item); $i++)
{
    $title = $xml->channel->item[$i]->title;
    $link = $xml->channel->item[$i]->link;
    $description = $xml->channel->item[$i]->description->children();
    // Or
    // $description = $xml->channel->item[$i]->description->p[0];
    $pubDate = $xml->channel->item[$i]->pubDate;

    $html .= "<a href='$link'><h3>$title</h3></a>";
    $html .= trim($description).'...';
    $html .= "<br />$pubDate";
}
echo $html;

【讨论】:

  • 它似乎不起作用。导致内部服务器错误500
  • 你应该检查你的服务器日志。这不是 PHP 问题。
  • 我刚刚注意到您的描述包含在 &lt;![CDATA[]]&gt; 中,这导致描述 SimpleXML 对象为空。您对此有任何控制权吗?
  • 我认为没有!由 WordPress 内部管理。即使有,我也不想更改默认设置。一定有办法克服。
  • 获取空白页面。 :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 2012-07-24
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
相关资源
最近更新 更多