tags:

views:

79

answers:

1

I'm trying to evaluate an xml node using xpath and i'm not sure why it's not evaluating to true.

xml

<?xml version="1.0"?>
<users>
    <user>
        <username>tom</username>
        <password>d644cd4b1c72f563855e689d46d9198e</password>
    </user>
    <user>
        <username>jeff</username>
        <password>smith</password>
    </user>
</users>

When i submit a form this script is called

    <?php
        //needed for firePHP in firebug
        include('FirePHPCore/fb.php');
        ob_start();

        $error = false;
        if(isset($_POST['login'])) {
            $username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
            $password = md5($_POST['password']);


            if(file_exists("../users.xml")) {

                $xmlobject = simplexml_load_file("../users.xml");
                fb("username is: ".$username); //returns tom
                fb($xmlobject->xpath("//*[username='tom']")); //returns the entire array of elements. How do i make it return just the node value?

                //why does this evaluate to false?
                if($username == $xmlobject->xpath("//*[username='tom']")) {
                    fb("got here");
                } else {
                    fb("got here instead");
                }   
            }
            $error = true;
 }
?>
+4  A: 

I'm an idiot.

Instead of this

if($username == $xmlobject->xpath("//*[username='tom']"))

I just needed to do this

if($xmlobject->xpath("//*[username='tom']"))

Now it checks if a node exists with the value tom.

Catfish
Wouldn't that check for an attribute "username"?
musicfreak
Nope. I tried it returns correct. I think [@username='tom'] would return an attribute.http://www.w3schools.com/xpath/xpath_syntax.asp
Catfish
Ah, got it. My XPath is a bit rusty. If you could edit your answer I'll give you a +1. :)
musicfreak
what would i edit? My answer's correct.
Catfish
I know, but I withdrew my +1 at first, and now it's not letting me give it back to you until you edit your answer. Just make a tiny change.
musicfreak
Don't `"//*[username='tom']"`, do `"/users/user[username='tom']"`. It's not only easier to read and more explicit, it's also *a lot* faster with big input documents.
Tomalak
@Tomalak thanks for the input. I'll change that. In my application, i'm trying to use it to store user information to login. This application is only going to have 1 user so it's not a big deal in this case but thanks for the tip.
Catfish