2015-03-13 126 views
0

我的XML文件的結構是:如何通過指定屬性在SimpleXML中獲取特定值?

<?xml version="1.0" encoding="UTF-8"?> 
.... 
.. 
. 
<usernames> 
    <user id="harrypotter"> 
    <topicid id="1"> 
     <commentid>1</commentid> 
    </topicid> 
    <topicid id="2"> 
     <commentid>2</commentid> 
    </topicid> 
    <topicid id="3"> 
     <commentid>3</commentid> 
    </topicid> 
    <topicid id="4"> 
     <commentid>4</commentid> 
    </topicid> 
    <topicid id="5"> 
     <commentid>5</commentid> 
    </topicid> 
    <topicid id="6"> 
     <commentid>6</commentid> 
    </topicid> 
    <topicid id="7"> 
     <commentid>7</commentid> 
    </topicid> 
    <topicid id="8"> 
     <commentid>8</commentid> 
    </topicid> 
    <topicid id="9"> 
     <commentid>9</commentid> 
    </topicid> 
    <topicid id="10"> 
     <commentid>10</commentid> 
    </topicid> 
    <topicid id="11"> 
     <commentid>11</commentid> 
    </topicid> 
    </user> 
    .... 
    .. 
    . 
</usernames> 

我有一個函數傳遞一個主題,即可獲得一個評論,一個用戶名。我的功能是:

function getComment($var_topicid, $usrname) 
$xml2=simplexml_load_file("comment.xml") or die("Error: Cannot create object"); 
foreach ($xml2->user as $user){ 
    if ($user['id'] == $usrname){ 
     if($user->topicid['id'] == $var_topicid){ 
      return $user->topicid->commentid; 
     } 
    } 
} 
} 

我嘗試通過傳遞值來獲得評論,但它不返回任何內容。

$x = getComment('2','harrypotter')); 
print $x; 

您能否給點建議?

謝謝。

回答

0

而且你不循環用戶節點上:在topicid,你應該添加一個foreach,它看起來應該像這樣:

function getComment($var_topicid, $usrname) 
    $xml2=simplexml_load_file("comment.xml") or die("Error: Cannot create object"); 
    foreach ($xml2->user as $user){ 
    if ($user['id'] == $usrname){ 
     foreach (user->topicid as $topic){ 
     if($topic['id'] == $var_topicid){ 
      return $topic->commentid; 
     } 
     } 
    } 
    } 
}