Search code examples
phpxmlxml-parsingdomparser

PHP DomParser getting option name and value from xml tag



I'm trying to parse an xml file with PHP.
I'm using this code and it works well for getting the tagname and the value:

function getChildNodes($dom,$SearchKey){

  foreach ($dom->getElementsByTagName($SearchKey) as $telefon) {
      foreach($telefon->childNodes as $node) {
          print_r(
          $SearchKey . " : " . $node->nodeValue . "\n"                
      );
  }

} }

example xml of working piece of code:

<inputs>
 <input>C:\Program Files\VideoLAN\VLC\airbag.mp3</input>
 <input>C:\Program Files\VideoLAN\VLC\sunpark.mp3</input>
 <input>C:\Program Files\VideoLAN\VLC\rapidarc.mp3</input>
</inputs>

example xml of not working piece of code:

<instances>
 <instance name="default" state="playing" position="0.050015" time="9290569" length="186489519" rate="1.000000" title="0" chapter="0" can-seek="1" playlistindex="3"/>
</instances>

Can someone help me figure out wich options I need to use for getting out the optioname and optionvalue?

all responses are appreciated


Solution

  • Here is a code sample for printing out the XML attributes:

    <?php
    
    $source = '<instances><instance name="default" state="playing" position="0.050015" time="9290569" length="186489519" rate="1.000000" title="0" chapter="0" can-seek="1" playlistindex="3"/></instances>';
    
    $doc = new DOMDocument();
    $doc->loadXML($source);
    
    $el = $doc->firstChild->firstChild;
    
    for ($i = 0; $i < $el->attributes->length; $i++) {
        $attr = $el->attributes->item($i);
        echo 'Name: '.$attr->name, "\n";
        echo 'Value: '.$attr->value, "\n";
    }
    

    Hope this helps.