2

I have this xml file:

<friends>
    <friend>
        <name>xxx</name>
        <pays>France</pays>
    </friend>
    <friend>
        <name>yyy</name>
        <country>France</country>
    </friend>
    <friend>
        <name>zzz</name>
        <country>USA</country>
    </friend>
</friends>

To get my data, I am using this php code:

$xml = simplexml_load_file('friends.xml');
$friendsXML = $xml->friend;

Which works fine, but returns all of the friends.

Now I want to retrieve only friends who are from France:

country = 'france'.

Can anyone help me doing that?

hakre
  • 193,403
  • 52
  • 435
  • 836
zakariag
  • 325
  • 2
  • 3
  • 14
  • simple xpath: `//country[text()='france']/..` – Marc B Jul 10 '15 at 17:25
  • Or perhaps better duplicate: [php simplexml get a specific item based on the value of a field](http://stackoverflow.com/q/17537909/367456) – hakre Jul 10 '15 at 17:35
  • Or perhaps the even better duplicate: [Implementing condition in XPath](http://stackoverflow.com/q/3448005/367456) – hakre Jul 10 '15 at 21:14

1 Answers1

2

I'd use XPath for things like this. Try:

 $res =  $xml->xpath('friend[country = "france"]');
 echo $res[0];
hakre
  • 193,403
  • 52
  • 435
  • 836
Andrey B
  • 99
  • 4