My code parses an array to get the paths to various attributes in an xml file. I load the xml as a simplexmlelement like so:
$xml = simplexml_load_string($xml_string);
$address = $xml->response->addressinformation->records->record[0];
This code will work and displays the correct value of '03':
$from = $address->{'from-date'}['month'];
echo $from;
//prints '03'
The {}
around from-date
are necessary because of the -
in the element name.
The following code blocks seem like they should be functionally equivalent to the above code, but when I assign the path to a $variable it does not work.
$path = "{'from-date'}['month']";
$from = $address->$path;
echo $from;
//prints ''
$path = "from-date['month']";
$from = $address->$path;
echo $from;
//prints ''
This code will work.
//normal path
$from = $address->{'from-date'};
//path assigned to variable
$path = "from-date";
$from2 = $address->$path;
var_dump($from);
var_dump($from2);
//both correctly output - object(SimpleXMLElement)#1587 (1)
//{ ["@attributes"]=> array(2) { ["year"]=> string(4) "2003" ["month"]=> string(2) "03" } }
It only seems to fail when I target the specific attribute with ['month']
. I know the answer to this question is just going to be some silly thing that I'm doing wrong. Can anyone tell me what it is?
Sample XML
$xml_string = '
<?xml version="1.0" encoding="utf-8"?>
<root>
<response>
<addressinformation>
<records>
<record id="1">
<fullname>JOHN E DOE</fullname>
<firstname>JOHN</firstname>
<middlename>E</middlename>
<lastname>DOE</lastname>
<fulldob>01/01/1970</fulldob>
<from-date year="2003" month="03"/>
<to-date year="2010" month="09"/>
</record>
<record id="2">
<fullname>JOHN E DOE</fullname>
<firstname>JOHN</firstname>
<from-date year="2003" month="03"/>
<to-date year="2010" month="09"/>
</record>
</records>
</addressinformation>
<otherinformation>
<records>
<record id="3">
<fullname>JOHN DOE</fullname>
<firstname>JOHN</firstname>
<lastname>DOE</lastname>
<fulldob>01/01/1970</fulldob>
</record>
<record id="4">
<fullname>JOHN EDWARD DOE</fullname>
<firstname>JOHN</firstname>
<middlename>EDWARD</middlename>
<lastname>DOE</lastname>
<fulldob>19700000</fulldob>
</record>
<record id="5">
<fullname>JOHN EDWARD DOE</fullname>
<firstname>JOHN</firstname>
<middlename>EDWARD</middlename>
<lastname>DOE</lastname>
<fulldob>19830000</fulldob>
</record>
</records>
</otherinformation>
</response>
</root>
';
question from:
https://stackoverflow.com/questions/65914698/php-simplexmlelement-fails-to-find-attribute-when-attribute-path-is-assigned-to 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…