How to search for an element in XML with PHP?

3

I'm starting to work with PHP now, so I do not know much. So, sorry if the question is too clueless.

I have an XML file type like this:

<usuários><br>
<fulano>
   <codigo>287983</codigo>
   <pontos>50</pontos>
   <nick>tal1</nick>
</fulano>
<ciclano>
   <codigo>455343</codigo>
   <pontos>80</pontos>
   <nick>tal2</nick>
</ciclano>
<beltrano>
   <codigo>233432</codigo>
   <pontos>60</pontos>
   <nick>tal3</nick>
</beltrano>
</usuarios>    

I wanted to know some PHP event that I could search for an element name and show your parents. Better detailing what I want to do. I have a text box where the visitor will type the username and search for it. Ai, the script will look in the XML for the name that was typed in any of the "nick" items, and thus return the parents' names. If you do not find it, return an error or something. For example, someone type the nick "tal2" in the text box and search, the script should return the value "Cyclan". The opposite can also be someone typing "Cyclan" and receiving "tal2" with an error message if you do not find it.

Any help is welcome.

    
asked by anonymous 10.02.2015 / 00:23

1 answer

1

You can use XPath:

Example:

$content = "<usuarios>
<fulano>
   <codigo>287983</codigo>
   <pontos>50</pontos>
   <nick>tal1</nick>
</fulano>
<ciclano>
   <codigo>455343</codigo>
   <pontos>80</pontos>
   <nick>tal2</nick>
</ciclano>
<beltrano>
   <codigo>233432</codigo>
   <pontos>60</pontos>
   <nick>tal3</nick>
</beltrano>
</usuarios>";
$xml = simplexml_load_string($content);
$list = $xml->xpath('//nick');
foreach($list as $nick) {
    if(strpos((string)$nick, 'tal1') !== false) {
        $person = $nick->xpath('..');
        echo "Found person: ";
        var_dump($person);
    }
}

link

    
11.02.2015 / 23:18