【问题标题】:PHP - How to get the key number from an XML object inside of a foreach loopPHP - 如何从 foreach 循环内的 XML 对象中获取键号
【发布时间】:2013-12-09 12:58:54
【问题描述】:
$data = simplexml_load_file($source_url);

如果我正在循环浏览一些看起来像这样的项目

    [item] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [title] => Justin Bieber and Chance the Rapper Collaborate
                        [link] => http://feedproxy.google.com/~r/absolutepunknet/~3/vn98Mqyr4_4/showthread.php
                        [pubDate] => Mon, 09 Dec 2013 07:37:44 GMT
                        [description] => SimpleXMLElement Object
                            (
                            )

                        [category] => News
                        [guid] => http://www.absolutepunk.net/showthread.php?t=3576311
                    )

                [1] => SimpleXMLElement Object
                    (
                        [title] => SimpleXMLElement Object
                            (
                            )

                        [link] => http://feedproxy.google.com/~r/absolutepunknet/~3/IjS0KtTy8Ws/showthread.php
                        [pubDate] => Mon, 09 Dec 2013 07:06:56 GMT
                        [description] => SimpleXMLElement Object
                            (
                            )

                        [category] => News
                        [guid] => http://www.absolutepunk.net/showthread.php?t=3576281
                    )

使用


foreach ($data->channel->item as $key => $value)

如何访问并可能删除其中一个对象,在此示例中,我想删除 [1] => SimpleXMLElementOjbect

我尝试过使用 $key 的值,但它只包含单词“item”。这个不太清楚。

【问题讨论】:

  • unset($data->channel->item[$key])foreach 内部工作吗?

标签: php xml object


【解决方案1】:

如果你想从 XML 元素中删除项目(而不是数组项目本身),你可以这样做:

$dom = dom_import_simplexml($element);
$dom->parentNode->removeChild($dom);

对于删除数组项@Dave Chen 的回答应该有效(我认为只能在 foreach 循环之外)

【讨论】:

    【解决方案2】:

    直接使用DOMDocument,DOMXpath查找节点:

    $dom = new DOMDocument();
    $dom->load($rssFile);
    $xpath = new DOMXpath($dom);
    
    //fetch the second item into a list
    $items = $xpath->evaluate('/rss/channel/item[2]');
    foreach ($items as $item) {
      // remove the item from its parent node
      $item->parentNode->removeChild($item);
    }
    
    echo $dom->saveXml();
    

    在 Xpath 列表中,位置从 1 而不是 0 开始。PHP 中的索引 1 是 Xpath 中的位置 2。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-29
      • 2017-11-08
      • 2017-07-04
      • 2017-04-13
      • 2016-09-26
      • 2012-07-19
      • 2012-06-15
      相关资源
      最近更新 更多