How to search for an element in XML with PHP?

Question:

I'm starting to work with PHP now so I don't know much. So sorry if the doubt is too clueless.

I have an XML file 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 look up an element name and show its parents. Better detailing what I want to do. I have a textbox where the visitor will type the username and search for it. Then, the script will look in the XML for the name that was typed in one of the "nick" items, and thus, return the parents' name. If you don't find it, it returns an error or something. For example, someone types the nickname "tal2" in the text box and search, the script should return the value "Ciclan". The opposite can also be, someone type "Ciclano" and receive "tal2" with an error message if he doesn't find it.

Every help is welcome.

Answer:

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

http://www.tuxradar.com/practicalphp/12/3/3

Scroll to Top
AllEscort