2013-12-12 2 views
0

제 질문은 PHP로 작성된 특정 파일에 XML 데이터를 저장하는 것과 관련이 있습니다. 그와PHP로 만든 페이지에 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 파일을 만들 :

이 내가 작업 한 XML,라는 파일 music.xml했다 말

// 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$xml->Musicians->Person으로 이미 채워지는 $instrument_by_names 인 노드 (사람 이름)의 텍스트를 포함해야합니다. 당신이 <persons> 요소와 상대하고 다음 루프에서 당신이 당신의 $instrument_loops을 개선해야 할 하나거야 현실적으로 $instrument_by_name->attributes()->instrument

를 통해 @instrument 속성 값을 가져 오는 것 때문에

$instrument_by_names 정말 $persons 호출해야

구조를 사용하거나 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; 
    } 
    } 

}