1

Is there a cleaner way to achieve this: The XML is:

            <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>

It works fine with the following just seems unwieldy. Is there a better way to get all the values for type, value and source?

             foreach($xml->Specifics as $specs) {
                    foreach($specs->Name as $name) {
                        foreach($name->children() as $child) {
                            echo $child->getName() . ": " . $child . "<br>";
                        }
                    }                   
                }
user2029890
  • 2,493
  • 6
  • 34
  • 65

2 Answers2

1

You can use Xpath. If I understand correctly you would like to iterate the name elements and read data from their children. SimpleXML has limited xpath support, too. But I prefer using DOM directly.

$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)
    ]
  );
}
ThW
  • 19,120
  • 3
  • 22
  • 44
0

Like ThW did answer, I'd say as well that xpath is the way to go to access Specifics/Names. As you tagged this simplexml, there's also some kind of shorty to obtain named values in your case:

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

Output:

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
)
Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836