PHP中按属性选择数据的XML

PHP中按属性选择数据的XML,php,xml,Php,Xml,我不确定这是否是最好的方法,但我有下面的XML文档,使用PHP我需要选择第一阶段中的数据 <?xml version="1.0" encoding="utf-8"?> <stages> <stage name="one"> <watch> <story> <title>title</title> <c

我不确定这是否是最好的方法,但我有下面的XML文档,使用PHP我需要选择第一阶段中的数据

<?xml version="1.0" encoding="utf-8"?>
<stages>
<stage name="one">
    <watch>
    <story>
        <title>title</title>
        <copy>text goes here</copy>
    </story>
    </watch>
</stage>
<stage name="two">
    <watch>
    <story>
        <title>title 2</title>
        <copy>text goes here</copy>
    </story>
    </watch>
</stage>
</stages>

也许XML应该是这样的

<stages>
<one>
    <watch>
    <story>
        <title>title</title>
        <copy>text goes here</copy>
    </story>
    </watch>
</one>
<two>
    <watch>
    <story>
        <title>title 2</title>
        <copy>text goes here</copy>
    </story>
    </watch>
</two>
</stages>

标题
这里有文字
标题2
这里有文字

阶段没有
名称
属性,它是一个属性

一个选项是使用xpath并获取阶段,其中键名的属性值为
One

/stages/stage[@name='one']
比如说

$xml = simplexml_load_file("content/content.xml");
$result = $xml->xpath("/stages/stage[@name='one']");
var_dump($result);
输出

array(1) {
  [0]=>
  object(SimpleXMLElement)#2 (2) {
    ["@attributes"]=>
    array(1) {
      ["name"]=>
      string(3) "one"
    }
    ["watch"]=>
    object(SimpleXMLElement)#3 (1) {
      ["story"]=>
      object(SimpleXMLElement)#4 (2) {
        ["title"]=>
        string(5) "title"
        ["copy"]=>
        string(14) "text goes here"
      }
    }
  }
}
array(1) {
  [0]=>
  object(SimpleXMLElement)#2 (2) {
    ["@attributes"]=>
    array(1) {
      ["name"]=>
      string(3) "one"
    }
    ["watch"]=>
    object(SimpleXMLElement)#3 (1) {
      ["story"]=>
      object(SimpleXMLElement)#4 (2) {
        ["title"]=>
        string(5) "title"
        ["copy"]=>
        string(14) "text goes here"
      }
    }
  }
}