2013-04-03 97 views
0

我想用PHP來處理幾個XML文件。我已經通讀了php simpleXML網站上的解釋和一些示例,但我無法從xml中獲得我想要的內容。
我無法控制xml。下面是XML文件的一個片段:麻煩與PHP和XML

<end-user-emails> 
    <user email="[email protected]"/> 
</end-user-emails> 

的代碼片段我目前有:

$result = $xml->xpath("end-user-emails/user[@email]"); 
print_r($result[0][email]); 

,輸出:

SimpleXMLElement Object ([0] => [email protected]) 

我無法找到一個方法來簡單地返回屬性值。
我已經嘗試將其轉換爲字符串並獲取錯誤。 我已經試過幾個變化:

$result = $xml->end-user-emails[0]->user[0]->attributes(); 

,它告訴我,儘管前面的輸出,我不能叫屬性(),因爲它不會被調用的對象上。因此,如果任何人都可以讓我知道如何從XML中獲取屬性名稱和值,那將是非常感謝。屬性名稱不nessasary,但我想用它,所以我可以確認我其實抓住電子郵件,是這樣的:

if attributeName = "email" then $email = attributevalue 
+1

爲什麼不使用'$ result [0] ['email'] [0]'? – 2013-04-03 19:56:56

+0

試過了,輸出沒變。 – 2013-04-03 20:00:26

+0

不確定,並且可能完全不相關,但在XML元素名稱中允許使用破折號? **更新**沒關係,破折號是允許的,而不是第一個字符。 – thaJeztah 2013-04-03 20:06:08

回答

2

attributes()方法將返回象對象數組所以這應該做你想要什麼,而只用PHP 5.4+

$str = ' 
<end-user-emails> 
    <user email="[email protected]"/> 
</end-user-emails>'; 
$xml = simplexml_load_string($str); 
// grab users with email 
$user = $xml->xpath('//end-user-emails/user[@email]'); 
// print the first one's email attribute 
var_dump((string)$user[0]->attributes()['email']); 

要去工作,如果你在php5.3上,你將不得不遍歷屬性(),如下所示:

foreach ($user[0]->attributes() as $attr_name => $attr_value) { 
    if ($attr_name == 'email') { 
     var_dump($attr_name, (string)$attr_value); 
    } 
} 

您可以指定返回值->attributes()並在該變量上使用['email']。如果您事先不知道屬性名稱,循環也很有用。

+0

嗯,這是問題,我使用php5.3,感謝您的幫助。 – 2013-04-03 20:24:56

1

要獲得用戶的電子郵件地址(在你的例子)加載XML到一個對象中,然後解析每個項目。我希望這有幫助。

//load the data into a simple xml object 
$xml = simplexml_load_file($file, null, LIBXML_NOCDATA); 
//parse over the data and manipulate 
foreach ($xml->action as $item) { 
    $email = $item->end-user-emails['email']; 
    echo $email; 

}//end for 

欲瞭解更多信息,請參閱http://php.net/manual/en/function.simplexml-load-file.php

+0

謝謝,這也適用。 – 2013-04-03 20:25:13