dongzhi6382 2015-03-13 19: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 21: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条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决