【问题标题】:Get the 18 first results in a SimpleXMLElement Object在 SimpleXMLElement 对象中获取 18 个第一个结果
【发布时间】:2012-01-11 12:14:25
【问题描述】:

我有这个 xml 响应,我会做一个

foreach($response->entry->item as $data)

但是 $data 包含的数组 (20) 比我需要的 (18) 多。所以我尝试做 array_slice 但你知道它不会工作。

我还可以尝试哪些其他解决方案?

【问题讨论】:

  • 大声笑,很明显......现在正在尝试。非常感谢。
  • 您可以像使用任何其他数组一样进行操作

标签: php xml-parsing slice


【解决方案1】:

您可以尝试通过 xpath 从您的 xml 中选择的数据限制结果集。

$string = <<<XML
<?xml version='1.0'?>
    <document>
        <item id="1" />
        <item id="2" />
        <item id="3" />
        <item id="4" />
        <item id="5" />
        <item id="6" />
    </document>
XML;

$xml = simplexml_load_string($string);
var_dump($xml->xpath("//item[@id>2 and @id<5]")) // Prints the two nodes matching the condition from the xpath

根据 cmets 的建议,您也可以使用 for 而不是 foreach 循环遍历数组并限制迭代次数。

【讨论】:

  • 我会按照@k102 的建议尝试 for,我认为这样会更好。 Tnx
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
相关资源
最近更新 更多