1

i have this xml 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>

I have tried to get the fields like this:

$xml = simplexml_load_file($xmlFile);

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

In my opinion this should output for RecNo_1 "19.11.1999", and for RecNo_2 "22.11.1999". But it outputs nothing... How can I simply get the values?

Nilse
  • 140
  • 9
  • This should help - http://stackoverflow.com/questions/992450/simplexml-selecting-elements-which-have-a-certain-attribute-value – Tom Mar 06 '17 at 13:58

1 Answers1

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
  }
}

Points:

  • Your XML is missing a root-node (i added one in my example)
  • I only access RecNo_1 directly, in good XML they should only be a node like RecNo (no numbers)
  • If you want the value from RecNo_2 you have to change the xpath

Short Version for all blocks in the example:

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

Have a nice.

JustOnUnderMillions
  • 3,741
  • 9
  • 12