通过PHP SimpleXMLElementObject迭代的通用解决方案

时间:2012-10-02 12:44:28

标签: php

  

可能重复:
  Parse XML sequentially in PHP

我希望能够使用PHP迭代SimpleXMLElementObject。但是,我希望能够在没有预先知道标签名称的情况下这样做 - 我想要一个可以用作对象键名的发现机制的通用解决方案。我尝试了一些'foreach'类型的解决方案,但无法让它工作。

示例代码:

$schema = new SimpleXMLElement("<activity></activity>");
$schema->addAttribute("default-currency","asdf");
$schema->addAttribute("last-updated-datetime","jkl;");
$schema->addChild('title', 'example title');

print_r($ schema)给出:

SimpleXMLElement Object ( 
    [@attributes] => Array ( 
        [default-currency] => asdf 
        [last- updated-datetime] => jkl; 
        ) 
    [title] => example title 
) 

由于

1 个答案:

答案 0 :(得分:0)

使用SimpleXMLElement的getName函数,它将为您提供标记名称

http://www.php.net/manual/en/simplexmlelement.getname.php

例如

$sxe = new SimpleXMLElement("xml file");

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
    echo $child->getName() . "\n";
}