0

I'm not sure if this is even the best way to do this, but I have the following XML document and using PHP I need to select the data that comes in stage one

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

This PHP returns NULL

$xml = simplexml_load_file("content/content.xml");
var_dump($xml->stage->name['one']);
milky_jay
  • 378
  • 1
  • 6
  • 17

2 Answers2

1

Stage does not have a name property, it is an attribute.

One option is to use xpath and get the stage(s) where the attribute value for key name is one:

/stages/stage[@name='one']

For example

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

Output

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"
      }
    }
  }
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

Perhaps the XML should be like this instead

<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>
milky_jay
  • 378
  • 1
  • 6
  • 17