将XML节点值放到用PHP创建的页面上


Putting XML Node Values Onto Pages Created With PHP

我的问题是将XML数据放到用PHP创建的特定文件中。

假设这是我正在使用的XML,一个名为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>

然后,我加载提要,并基于"instrument"属性创建PHP文件:

// 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);
}

这样就可以毫不费力地创建吉他.php、贝斯.php和鼓点.php$page_data也会写在页面上,但这就是我被难住的地方。

我希望将相应的节点值放在每一页上。因此,"Clapton,Eric"、"Hendrix,Jimi"、"Page,Jimmy"将出现在吉他.php上,"McCartney,Paul"将显示在贝斯.php上,而"Moon,Keith"将显示于drum.php上。我该怎么做呢?

(string) $instrument_by_name应包含该节点的文本(人名),因为$instrument_by_names已由$xml->Musicians->Person填充。

$instrument_by_names实际上应该被称为$persons,因为您正在处理<persons>元素,然后在循环中通过$instrument_by_name->attributes()->instrument 获取@instrument属性值

实际上,您要么必须改进$instrument_loops结构,要么考虑使用xpath查询XML结构。

// 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;
    }
  }
}