2010-02-28 41 views
0

我試圖評估一個xml節點使用XPath,我不知道它爲什麼不評估爲真。爲什麼這個xpath沒有評估爲真?

XML

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

當我提交表單來調用此腳本

<?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

取而代之的是

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

我只需要做到這一點

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

現在,它檢查節點值"tom"是否存在至少一個節點<username>

+0

不會檢查屬性「用戶名」嗎? – 2010-02-28 21:57:24

+0

沒有。我試過它返回正確。我認爲[@ username ='tom']會返回一個屬性。 http://www.w3schools.com/xpath/xpath_syntax.asp – Catfish 2010-02-28 22:03:58

+0

啊,明白了。我的XPath有點生疏。如果你可以編輯你的答案,我會給你一個+1。 :) – 2010-02-28 22:05:08

相關問題