I have a piece of XML which is as follows
firstname
mid
You problem is when you do
$currentRecord->$dateFirst['month']
PHP will first evaluate $dateFirst['month']
as a whole before trying to use it as a property
$dateFirst = 'date-first';
var_dump( $dateFirst['month'] ); // gives "d"
because strings can be accessed by offset with array notation, but non-integer offsets are converted to integer and because casting 'month' to integer is 0, you are trying to do $currentRecord->d
:
$xml = <<< XML
<record>
<date-first month="jan"/>
<d>foo</d>
</record>
XML;
$record = simplexml_load_string($xml);
$var = 'date-first';
echo $record->$var['month']; // foo
You can access hyphenated properties with curly braces:
$record->{'date-first'}['month'] // jan
On a sidenote, when the XML shown in your question is really the XML you are loading with SimpleXml, e.g. when <records>
is the root node, then doing
$reportDataXmlrecords->records->record
cannot work, because $reportDataXmlrecords
is already the root node and you'd have to omit the ->records
if you want to iterate over the record elements in it.