dongzhi6382 2015-03-13 11:35
浏览 44
已采纳

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

The structure of my XML file is:

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

I have a function to get a comment by passing a topic, and a username. My function is:

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

I try to get a comment by passing the values, but it does not return anything.

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

Could you please give some suggestion?

Thank you.

展开全部

  • 写回答

2条回答 默认 最新

  • dtdb99743 2015-03-13 13:08
    关注

    I found a solution by applying xpath:

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

    More details: SimpleXML: Selecting Elements Which Have A Certain Attribute Value

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部