How to search for an element in XML with PHP?

Asked

Viewed 691 times

3

I’m starting to work with PHP now, so I don’t know much about it. So I’m sorry if the doubt is too much.

I have a type 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 search for an element name and show your parents. Detailing better what I want to do. I have a text box where the visitor will write the username and search for it. Ai, the script will search the XML for the name that was typed on one of the "nick" items, and thus return the parents' name. In case you don’t think so, make a mistake or something. For example, someone type the nick "tal2" in the text and search box, the script should return the value "Ciclano". The opposite may also be, someone type "Ciclano" and receive "tal2" with an error message if you do not think.

Any help is welcome.

  • I advise you to take a look here: http://php.net/manual/en/refs.xml.php. This reply may also help you: http://answall.com/a/15452/14674

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.