2013-04-03 109 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