display data from XML using php simplexml

两盒软妹~` 提交于 2019-12-02 02:53:43

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!