0

my question has to do with putting XML data onto specific files that have been created with PHP.

Say this was the XML I was working with, a file called music.xml:

<XML_DATA item=“MusicBands”>
    <Musicians>
        <Person instrument="guitar">Clapton, Eric</Person>
        <Person instrument="guitar">Hendrix, Jimi</Person>
        <Person instrument="bass">McCartney, Paul</Person>
        <Person instrument="drums">Moon, Keith</Person>
        <Person instrument="guitar">Page, Jimmy</Person>
    </Musicians>
</XML_DATA>

With that, I load the feed, and create PHP files based on the "instrument" attribute:

// Loads the xml feed
$xml = simplexml_load_file("http://example.com/music.xml");
$instrument_by_names = $xml->Musicians->Person;

// This is to make sure repeat attribute values don't repeat
$instrument_loops = array();
foreach($instrument_by_names as $instrument_by_name){
    $instrument_loops[] = (string) $instrument_by_name->attributes()->instrument;
}
$instrument_loops = array_unique($instrument_loops);

// This is where I need help
foreach($instrument_loops as $instrument_loop){
    $page_url = $instrument_loop.'.php';
    $my_file = $page_url;
    $handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
    $page_data = 'Here lays the issue.';
    fwrite($handle, $page_data);
}

This creates guitar.php, bass.php, and drums.php without trouble. $page_data also gets written on the pages, but this is where I'm stumped.

I would like to have the corresponding node values put on each page. So "Clapton, Eric", "Hendrix, Jimi", "Page, Jimmy" would be on guitar.php, "McCartney, Paul" would be on bass.php, and "Moon, Keith" would be on drums.php. How would I go about doing this?

user1339316
  • 75
  • 2
  • 9

1 Answers1

0

(string) $instrument_by_name should contain the text of that node (persons name) as $instrument_by_names is being populated by $xml->Musicians->Person already.

$instrument_by_names should really be called $persons since you're dealing with the <persons> element and then in your loop you're fetching the @instrument attribute value via $instrument_by_name->attributes()->instrument

Realistically you're going to either have to improve your $instrument_loops structure, or look at using xpath to query your XML structure.

// This is where I need help
foreach($instrument_loops as $instrument_loop){

  // get all the persons with a @instrument of $instrument_loop
  if($persons = $xml->xpath('//Person[@instrument="'.$instrument_loop.'"]'))
  {
    foreach($persons as $person)
    {
      echo $person;
    }
  }

}
Scuzzy
  • 12,186
  • 1
  • 46
  • 46