2013-12-12 85 views
0

我的問題與將XML數據放到使用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> 

就這樣,我加載進料,並創建一個基於「工具」屬性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); 
} 

這創建了guitar.php,bass.php和drums.php沒有麻煩。 $ page_data也寫在頁面上,但這是我難倒的地方。

我想在每個頁面上放置相應的節點值。因此,「Clapton,Eric」,「Hendrix,Jimi」,「Page,Jimmy」將在guitar.php上,「McCartney,Paul」將在bass.php上,而「Moon,Keith」將在drums.php上。我會如何去做這件事?

回答

0

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

}