2014-05-01 161 views
0

是否有一个更清洁的方式来实现这一目标: 的XML是:PHP循环通过XML嵌套循环没有多个foreach循环?

  <Specifics> 
       <Name> 
        <Type>Brand</Type> 
        <Value>Apple</Value> 
        <Source>list</Source> 
       </Name> 
       <Name> 
        <Type>Country</Type> 
        <Value>USA</Value> 
        <Source>list</Source> 
       </Name> 
       <Name> 
        <Type>Rating</Type> 
        <Value>87</Value> 
        <Source>list</Source> 
       </Name> 
       <Name> 
        <Type>Project</Type> 
        <Value>Dolphin</Value> 
        <Source>list</Source> 
       </Name> 
       <Name> 
        <Type>Age</Type> 
        <Value>10-20</Value> 
        <Source>list</Source> 
       </Name> 
      </Specifics> 

它工作正常似乎只是笨拙以下。有没有更好的方法来获得type,valuesource的所有值?

   foreach($xml->Specifics as $specs) { 
        foreach($specs->Name as $name) { 
         foreach($name->children() as $child) { 
          echo $child->getName() . ": " . $child . "<br>"; 
         } 
        }     
       } 
+0

你可以使用递归的每个元素及其子迭代。 – CoDEmanX

回答

1

您可以使用Xpath。如果我理解正确,你想迭代name元素并从他们的孩子读取数据。 SimpleXML也具有有限的xpath支持。但我更喜欢直接使用DOM。

$dom = new DOMDocument(); 
$dom->loadXml($xml); 
$xpath = new DOMXpath($dom); 

// iterate all `Name` elements anywhere in the document 
foreach ($xpath->evaluate('//Name') as $nameNode) { 
    var_dump(
    [ 
     // fetch first `Type` element in $nameNode and cast it to string 
     $xpath->evaluate('string(Type)', $nameNode), 
     $xpath->evaluate('string(Value)', $nameNode), 
     $xpath->evaluate('string(Source)', $nameNode) 
    ] 
); 
} 
0

像THW did answer,我想说,以及该XPath是去访问Specifics/Names的方式。当你标记这个simplexml的,还有还有某种矮个子,你的情况,获得命名的值:

foreach ($xml->xpath('/*//Specifics/Name') as $name) 
{ 
    print_r(array_map('strval', iterator_to_array($name))); 
} 

输出:

Array 
(
    [Type] => Brand 
    [Value] => Apple 
    [Source] => list 
) 
Array 
(
    [Type] => Country 
    [Value] => USA 
    [Source] => list 
) 
Array 
(
    [Type] => Rating 
    [Value] => 87 
    [Source] => list 
) 
Array 
(
    [Type] => Project 
    [Value] => Dolphin 
    [Source] => list 
) 
Array 
(
    [Type] => Age 
    [Value] => 10-20 
    [Source] => list 
)