2013-10-18 95 views
0

我需要得到一個屬性:如何使用php獲取xml屬性?

<Info InstallPath="C:\Program Files\MyProg" Version="1.0" > 

    <Modules> 
     <parser.exe Launched="Off" /> 
     <analyzer.exe Launched="On" /> 
    </Modules> 

</Info> 

我寫道:

echo $Parser = $xml->Info->Modules->parser.exe->attributes()->Launched; 

但它不工作,因爲 「parser.exe」 包含一個圓點

Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ',' or ';'

+1

順便說一句,這個問題是相當普遍的初學者,它是一樣的破折號:http://stackoverflow.com/questions/9951753/php-simplexml-load-file-with-a-dash - 錯誤寫出根元素的名稱也是一個常見的錯誤。所有這些問題都得到了很好的解釋,並且在http://php.net/simplexml.examples-basic(示例#2和#3)中進行了很好的說明。 – hakre

回答

1

如果<Info>是你的根元素然後:

echo $xml->Modules->{'parser.exe'}->attributes()->Launched; 

因爲在你<parser.exe>元素的.字符,你需要使用{}語法來訪問屬性。

在SimpleXML中,對象($xml)引用根元素,所以$xml->Info不是必需的。