2017-03-06 53 views
1

我有这个XML文件:PHP使用simplexml_load_file相同的属性

<RecNo_1> 
<Field Name="erfdat">19.11.1999</Field> 
<Field Name="erfuser">user1</Field> 
<Field Name="l_dat">18.12.2014</Field> 
<Field Name="l_user">deluser1</Field> 
</RecNo_1> 

<RecNo_2> 
<Field Name="erfdat">22.11.1999</Field> 
<Field Name="erfuser">user2</Field> 
<Field Name="l_dat">18.12.2015</Field> 
<Field Name="l_user">deluser2</Field> 
</RecNo_2> 

我试图让字段是这样的:

$xml = simplexml_load_file($xmlFile); 

foreach($xml->children() as $ob) { 
    var_dump($ob->Name["erfdat"]); 
} 

在我看来这应该RecNo_1“1999年11月19日”输出,RecNo_2“22.11.1999”。但它不输出任何内容......我怎样才能简单地得到这些值?

+0

这将有助于 - http://stackoverflow.com/questions/992450/simplexml-selecting-elements-which-have-a-certain-attribute-value – Tom

回答

1
$xml = '<root> 
<RecNo_1> 
<Field Name="erfdat">19.11.1999</Field> 
<Field Name="erfuser">user1</Field> 
<Field Name="l_dat">18.12.2014</Field> 
<Field Name="l_user">deluser1</Field> 
</RecNo_1> 
<RecNo_2> 
<Field Name="erfdat">22.11.1999</Field> 
<Field Name="erfuser">user2</Field> 
<Field Name="l_dat">18.12.2015</Field> 
<Field Name="l_user">deluser2</Field> 
</RecNo_2> 
</root>'; 

$xml = simplexml_load_string($xml); 

$result = $xml->xpath('RecNo_1/Field'); 

while(list(,$node) = each($result)) { 
    if("erfdat"==(string)$node['Name']){ 
    print $node;#shows once 19.11.1999 
    } 
} 

点:

  • 你的XML是缺少一个根节点(我增加了一个在我的例子)
  • 我只能访问RecNo_1直接,良好的XML,他们应该只是像一个节点RecNo(无编号)
  • 如果从RecNo_2想要的值,你必须改变xpath

精简版在例如所有块:

$xml = simplexml_load_string($xml); 
for($i=1;$i<=2;$i++){ 
    $result = $xml->xpath("RecNo_{$i}/Field[@Name='erfdat']"); 
    print (string)$result[0]; 
} 

有一个愉快的。

+0

非常感谢您!这正是我需要的! – Nilse

相关问题