0

XML file contains:

<list1>
  <dzial>
    <ofert>
      <param name="surname" type="text">Something</param>
      <param name="number" type="text">4234-343-3</param>
    </ofert>
  </dzial>
</list1>

If I want to get "surname" parameter then I can use this code:

$xml = simplexml_load_file('test.xml');

if ($xml->list1[0]->dzial[0]->ofert[0]->param[0]=="Something") 
  echo "works!";

But I want to do it in different way. I want to select parameter according its attribute name="surname". How can I do that?

echo $xml->list1[0]->dzial[0]->ofert[0]->param[???];
Florent
  • 12,310
  • 10
  • 49
  • 58
Lucas
  • 2,924
  • 8
  • 27
  • 32

2 Answers2

3

You can use xpath, as explained in this answer: SimpleXML: Selecting Elements Which Have A Certain Attribute Value

$simplexml->xpath('/object/data[@attribute="value"]');
Community
  • 1
  • 1
Luca
  • 132
  • 3
1

Use XPath:

$xml = simplexml_load_file('test.xml');
$nodes = $xml->xpath('//param[@name="surname"]');

if (!empty($nodes)) {
    echo $nodes[0];
}
Florent
  • 12,310
  • 10
  • 49
  • 58