display data from XML using php simplexml

后端 未结 1 888
夕颜
夕颜 2021-01-23 18:43

I have a piece of XML which is as follows


  
    firstname
    mid         


        
相关标签:
1条回答
  • 2021-01-23 19:01

    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.

    0 讨论(0)
提交回复
热议问题