2009-07-16 17 views
2

ちょっと、xmlを解析したいのですが、1つの要素から同じタグを取得する方法がわかりません。SimpleXML 1要素のタグ

私は、この解析したい:だから私はジョンが話す言語を解析する

<profile> 
    <name>john</name> 
    <lang>english</lang> 
    <lang>dutch</lang> 
</profile> 

を。どうやってやるの ?

答えて

2

あなたは要素ノードを超えるforeachループを実行することができます:これはlang任意の数の要素を処理することができるという利点を有する

$xml_profiles = simplexml_load_file($file_profiles); 

foreach($xml_profiles->profile as $profile) 
{ //-- first foreach pulls out each profile node 

    foreach($profile->lang as $lang_spoken) 
    { //-- will pull out each lang node into a variable called $lang_spoken 
     echo $lang_spoken; 
    } 
} 

あなたは各プロフィール要素に対して持っているか持っていないかもしれません。

2
$profile->lang[0] 
$profile->lang[1] 
あなたがそうのようにSimpleXMLをしてそれを引っ張ってきた後
1

重複したXMLノードは配列のように動作すると考えてください。他が指摘したように

あなたはRSSが作業をフィードする方法これはサイドノートとしてはブラケットの構文

myXML->childNode[childIndex] 

と子ノードにアクセスすることができます。あなたは複数気付くでしょう

<item> 
</item> 

<item> 
</item> 

<item> 
</item> 

RSS XMLのタグ内のタグ。 RSSリーダーは、リストを要素の配列として扱うことによって、この問題を毎日処理します。

これはループバックできます。

0

また

$xProfile = simplexml_load_string("<profile>...</profile>"); 
$sName = 'john'; 
$aLang = $xProfile->xpath("/profile/name[text()='".$sName."']/lang"); 
// Now $aLang will be an array of lang *nodes* (2 for John). Because they 
// are nodes you can still do SimpleXML "stuff" with them i.e. 
// $aLang[0]->attributes(); --which is an empty object 
// or even 

$sPerson = (string)$aLang[0]->xpath('preceding-sibling::name'); 
// of course you already know this... but this was just to show what you can do 
// with the SimpleXml node. 
のように、特定の要素の配列を収集するためにXPathを使用することができます
関連する問題