Search code examples
phpjsonxmlsimplexml

How to parse XML-file to array and retrieve all children of an child with specific attribute in PHP?


my XML-file is as follows: agents.xml

<?xml version="1.0" encoding="UTF-8"?>
<agents>
  <agent id="1">
    <aname>pi1</aname>
    <alive>0</alive>
    <scenarios>1,2,3</scenarios>
  </agent>
  <agent id="2">
    <aname>pi2</aname>
    <alive>1</alive>
    <scenarios>4,5,6</scenarios>
  </agent>
</agents> 

I want to retrieve all child elements of an agent, selected by attribute value "id". I tried the following, passing a the variable "id" to the script:

$agents_xml = simplexml_load_file("/<path_to>/agents.xml");
$json = json_encode($agents_xml);
$array = json_decode($json,TRUE);
//decrement id for correct index
$id=$id-1;
//I want to return in JSON format
$testarr=json_encode($array['agent'][$id]);
echo $testarr;

When "id" has value 1, i got this:

{"@attributes":{"id":"1"},"aname":"pi1","alive":"0","scenarios":"1,2,3"}

But i know, if the XML is disordered like:

<?xml version="1.0" encoding="UTF-8"?>
<agents>
  <agent id="2">
    <aname>pi2</aname>
    <alive>1</alive>
    <scenarios>4,5,6</scenarios>
  </agent>
  <agent id="1">
    <aname>pi1</aname>
    <alive>0</alive>
    <scenarios>1,2,3</scenarios>
  </agent>
</agents> 

This is not very reliable.

Thanks for any idea!


Solution

  • Try

    $str = <<<XML
    <?xml version="1.0" encoding="UTF-8"?>
    <agents>
      <agent id="1">
        <aname>pi1</aname>
        <alive>0</alive>
        <scenarios>1,2,3</scenarios>
      </agent>
      <agent id="2">
        <aname>pi2</aname>
        <alive>1</alive>
        <scenarios>4,5,6</scenarios>
      </agent>
    </agents> 
    XML;
    
    $xml = new SimpleXMLElement($str);
    foreach($xml->agent as $agent)
    {
        var_dump($agent);
        echo "<hr>";
    }