0

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! But, the XML is an online file. How to do this with a XML-file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.