Rick de Jong
Rick de Jong

Reputation: 237

Get values from tag from XML using PHP DOMDocument

I have a XML file with the following contents:

<Klassen>
  <Klas>
     <Klas>HT1</Klas>
     <Omschrijving>Klas HT1</Omschrijving>
  </Klas>
  <Klas>
     <Klas>HT2</Klas>
     <Omschrijving>Klas HT2</Omschrijving>
  </Klas>
</Klassen>

I want to get the values from the second level Klas tag. I used the following PHP script, but it doesn't work;

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load($apiurl);
$hallo = $xmlDoc->getElementsByTagName('Klas');

foreach ($hallo as $book) {
   $result = $book->nodeValue;
   echo '<option value="'.$result.'">'.$result.'</option>';
}
?>

I can't change the tag names because it's not my API and also the creator of the API won't change it. What can I do to get the values (in this example) HT1 and HT2 into the select box?

Thank you!

Upvotes: 0

Views: 75

Answers (1)

Rolando Isidoro
Rolando Isidoro

Reputation: 5114

Here's a solution for you using DOMXpath:

<?php
    $xml = <<<XML
<Klassen>
  <Klas>
     <Klas>HT1</Klas>
     <Omschrijving>Klas HT1</Omschrijving>
  </Klas>
  <Klas>
     <Klas>HT2</Klas>
     <Omschrijving>Klas HT2</Omschrijving>
  </Klas>
</Klassen>
XML;


    $xmlDoc = new DOMDocument();
    $xmlDoc->loadXML($xml);

    $xpath = new DOMXpath($xmlDoc);
    $hallo = $elements = $xpath->query("//Klas/Klas");

    foreach ($hallo as $book) {
        $result = $book->nodeValue;
        echo '<option value="'.$result.'">'.$result.'</option>';
    }

Output:

<option value="HT1">HT1</option><option value="HT2">HT2</option>

Here's an online working example.

Upvotes: 1

Related Questions