arok
arok

Reputation: 1845

Read XML file from php

I have an issue reading this XML data.

<?xml version="1.0"?>
<DOCUMENT>
    <VERSION>2.0</VERSION>
    <MESSAGES>
        <MESSAGE>
            <SEND_DATE>2014-02-26</SEND_DATE>
            <ENTITY_ID>7002</ENTITY_ID>
            <RECIPIENT_NUM>xxxxxxxxxxxxxx</RECIPIENT_NUM>
            <MESSAGE_PARAMS>
                <DEN_SURNAME>Roze</DEN_SURNAME>
                <APPT_DATE>27/02/14</APPT_DATE>
                <APPT_TIME>09:00</APPT_TIME>
            </MESSAGE_PARAMS>
        </MESSAGE>
        <MESSAGE>
            <SEND_DATE>2014-02-26</SEND_DATE>
            <ENTITY_ID>7002</ENTITY_ID>
            <RECIPIENT_NUM>xxxxxxxxxxxx</RECIPIENT_NUM>
            <MESSAGE_PARAMS>
                <DEN_SURNAME>Roze</DEN_SURNAME>
                <APPT_DATE>27/02/14</APPT_DATE>
                <APPT_TIME>09:00</APPT_TIME>
            </MESSAGE_PARAMS>
        </MESSAGE>
        <MESSAGE>
            <SEND_DATE>2014-02-26</SEND_DATE>
            <ENTITY_ID>7002</ENTITY_ID>
            <RECIPIENT_NUM>xxxxxxxxxxxxxx</RECIPIENT_NUM>
            <MESSAGE_PARAMS>
                <DEN_SURNAME>Roze</DEN_SURNAME>
                <APPT_DATE>27/02/14</APPT_DATE>
                <APPT_TIME>09:00</APPT_TIME>
            </MESSAGE_PARAMS>
        </MESSAGE>
    </MESSAGES>
</DOCUMENT>

I have a <MESSAGES> tag containing several <MESSAGE> tags containing different values. I am currently using this code to read the values inside each <MESSAGE> tag.

$dr_name=$xml->MESSAGES->MESSAGE->MESSAGE_PARAMS->DEN_SURNAME;
$apt_date= $xml->MESSAGES->MESSAGE->MESSAGE_PARAMS->APPT_DATE;
$apt_time= $xml->MESSAGES->MESSAGE->MESSAGE_PARAMS->APPT_TIME;

I am getting only the values for the first <MESSAGE> tag.

How can I read all the <MESSAGE> tags?

Upvotes: 0

Views: 85

Answers (1)

artuc
artuc

Reputation: 913

The problem is simplexml object was returning the first record (0). So in your code you need to loop the Messages->message tag to reach them all. You can use this code to fetch all messages:

$file = 'data.xml';
$oXml = simplexml_load_file($file);
if($oXml){
    if(count($oXml->MESSAGES->MESSAGE) > 0){
        foreach($oXml->MESSAGES->MESSAGE as $m){
        echo 'Sent: '.$m->SEND_DATE.'<br />';
    echo 'ID: '.$m->ENTITY_ID.'<br />';
    echo 'ID: '.$m->RECIPIENT_NUM.'<br />';
    echo 'Surname: '.$m->MESSAGE_PARAMS->DEN_SURNAME.'<br /><hr /><br />';
    }
    }
}

Upvotes: 3

Related Questions