2012-08-12 72 views
0

這是我想要做的。如何使用字符串訪問對象的圖層?

我讀了一個XML文件,需要訪問某些屬性。問題是這個XML文件可能有4種配置之一。

我希望能夠做的是一樣的東西:

if(condition1){ 
    $title='PropertyParent->Child'; 
} 
elseif(condition2){ 
    $title='DifferentProperty->AnotherLayer->DifferentChild'; 
} 

$myTitle = $xml->$title; 

,並將它在字符串中訪問對象的結構。有沒有辦法做到這一點?我應該使用變量嗎?

感謝您的幫助。

回答

0

好,要做到這一點的唯一方法是使用自己的函數:

function return_nested($xml_file, $condition) 
{ 
    $cond_arr = explode("->", $condition); 
    $document = new DOMDocument(); 
    $document->load($xml_file); 
    foreach($cond_arr as $cond) 
    { 
     $document = $document->getElementsByTagName($cond)->item(0); //process each condition 
    } 
    return $document; //return element 
} 
相關問題