如何将 XML-file 解析为数组并检索 PHP 中具有特定属性的子项的所有子项?

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

我的XML-文件如下: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> 

我想检索由属性值 "id" 选择的代理的所有子元素。我尝试了以下操作,将变量 "id" 传递给脚本:

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

当 "id" 的值为 1 时,我得到了这个:

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

但我知道,如果 XML 像这样乱序:

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

这个不太靠谱

感谢任何想法!

尝试

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