tags:

views:

171

answers:

3

I have an XML file that needs parsing in PHP. I am currenlty using simplexml_load_file to load the file like so:

$xml = simplexml_load_file('Project.xml');

Inside that XML file lies a structure like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<project>
<name>Project 1</name>
<features>
    <feature>Feature 1</feature>
    <feature>Feature 2</feature>
    <feature>Feature 3</feature>
    <feature>Feature 4</feature>
</features>
</project>

What I am trying to do is print the <name> contents along with EACH <feature> element within <features>. I'm not sure how to do this because there is more than 1 element called <feature>. Any help is greatly appreciated.

+1  A: 

to print the text, try this :

foreach($xml->features->feature as $key => $value)
{
    echo $value;
}
Puaka
Works perfectly, thanks.
Nate Shoffner
A: 

You can do:

foreach($xml->features->feature as $f) {
    echo $f."\n";
}
codaddict
A: 

simplexml_load_file() returns an object.

Have a look at the structure with var_dump($xml):

object(SimpleXMLElement)#1 (2) {
  ["name"]=>
  string(9) "Project 1"
  ["features"]=>
  object(SimpleXMLElement)#2 (1) {
    ["feature"]=>
    array(4) {
      [0]=>
      string(9) "Feature 1"
      [1]=>
      string(9) "Feature 2"
      [2]=>
      string(9) "Feature 3"
      [3]=>
      string(9) "Feature 4"
    }
  }
}

So code like this:

<?PHP
$xml = simplexml_load_file('test.xml');
echo $xml->name . "\n";
foreach($xml->features->feature as $f){
  echo "\t$f\n";
}

Will produce output like:

Project 1
    Feature 1
    Feature 2
    Feature 3
    Feature 4

Which is what I assume you're after, more or less.

timdev