使用SimpleXML计算XML元素/节点数

3

可能会有重复,但我迄今为止没有找到有用的东西。

我正在尝试使用simplexml计算XML文件中的节点/子节点数量。

我尝试了以下代码。

$xml = simplexml_load_file("./file.xml");
echo count($xml->rss->channel->item);

并且

echo count($xml->item);

但仅仅输出0

这里是XML的快照。

<?xml version="1.0"?>
<rss xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:g="http://base.google.com/ns/1.0" version="2.0">
  <channel>
    <item>
      <title>PUDRA Pudra Ceket Ceket</title>
      <link>http://www.trendyol.com//Pudra-Ceket-IW6140005046/UrunDetay/31066/9188683?</link>
       <description>36 pudra pudra ceket ıw6140005046 ipekyol ceket kadın</description>
       <g:urunid>1423905</g:urunid>
       <g:id>1423905_14</g:id>
    </item>
    <item>
        ....
    </item>

在打印单个项目时,它没有选择“<g:id>1423905_14</g:id>”。 - Mubin
1个回答

4
这对您应该有效:
echo count($xml->channel->item);

编辑:

为什么要这样做?因为通过 simplexml_load_file(),你会得到一个像这样的结构体(print_r($xml);):

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [version] => 2.0
        )

    [channel] => SimpleXMLElement Object
        (
            [item] => Array
                (

由于这种结构,您必须像我上面说的那样访问对象。

谢谢。再多帮助一点,当我尝试打印产品,例如 print_r($xml->channel->item);。它只打印了那些没有 g: 的节点,例如描述、标题、链接等。如何获取其余部分呢? - Mubin
1
@MubinKhalid 这些元素位于不同的 XML 命名空间中,如果您想访问它们,请参见此处:http://blog.sherifmansour.com/?p=302 - Rizier123

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接