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 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度