Search code examples
phpsimplexml

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


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.


Solution

  • 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