如何通过指定的属性获取 SimpleXML 中的特定值?

How to get a specific value in SimpleXML by specified attributes?

我的 XML 文件的结构是:

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

我试图通过传递值来获得评论,但它没有 return 任何东西。

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

能给点建议吗?

谢谢。

我通过应用 xpath 找到了解决方案:

$myDataObjects = $xml2->xpath('//usernames/user[@id="harrypotter"]/topicid[@id="2"]/commentid');

print $myDataObjects[0][0];

更多详情:SimpleXML: Selecting Elements Which Have A Certain Attribute Value

此外,您没有在用户节点上循环: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;
        }
      }
    }
  }
}