Newbie Coder
Newbie Coder

Reputation: 10942

How to get the value of an xml sub element using DOMDocument methods?

I am new to PHP and XML.

Can somebody tell me how can I get the values of a sub element or child node of a an xml element?

index.php

$domdoc = new DOMDocument(); 
$domdoc->load('actionstars.xml'); 

foreach ($domdoc->getElementsByTagName("actionstar") as $star) {
 echo $star->item(0)->nodeValue; // displays the <id> element
 echo $star->item(1)->nodeValue; // displays the <name> element
 echo "<br />";
} 


actionstars.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<actionstars>
 <actionstar>
  <id>1</id>
  <name>Jean Claude Van Damme</name>
 </actionstar>
 <actionstar>
  <id>2</id>
  <name>Scott Adkins</name>
 </actionstar>
 <actionstar>
  <id>3</id>
  <name>Dolph Ludgren</name>
 </actionstar>
 <actionstar>
  <id>4</id>
  <name>Michael Jai White</name>
 </actionstar>
 <actionstar>
  <id>5</id>
  <name>Michael Worth</name>
 </actionstar>
</actionstars>

Pls help...

Upvotes: 0

Views: 462

Answers (1)

alex
alex

Reputation: 490153

If you can guarantee their order, you can use childNodes and the offset, otherwise...

$domdoc = new DOMDocument(); 
$domdoc->load('actionstars.xml'); 

foreach ($domdoc->getElementsByTagName("actionstar") as $star) {
 echo $shit->getElementsByTagName('id')->item(0)->nodeValue; // displays the <id> element
 echo $shit->getElementsByTagName('name')->item(0)->nodeValue; // displays the <name> element
 echo "<br />";
} 

Upvotes: 3

Related Questions