Search code examples
phpxmlloopsnamespacessimplexml

looping in namespaced XML


I have this XML :

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <ns2:ReadPNRResponseBody xmlns="http://trippro.com/webservices/common/v2" xmlns:ns2="http://trippro.com/webservices/readpnr/v2">
            <ns2:ReadPNRResponse>
                <ns2:PaxDetail>
                    <PaxRef>1</PaxRef>
                    <PaxType>ADT</PaxType>
                    <FirstName>JOHN</FirstName>
                    <MiddleName>ADAM</MiddleName>
                    <LastName>DOE</LastName>
                    <Gender>M</Gender>
                    <DateOfBirth>08/15/1983</DateOfBirth>
                    <PassportNumber>9DUSIJH232</PassportNumber>
                    <Nationality>IN</Nationality>
                    <CountryOfIssue>US</CountryOfIssue>
                </ns2:PaxDetail>
                <ns2:PaxDetail>
                    <PaxRef>1</PaxRef>
                    <PaxType>ADT</PaxType>
                    <FirstName>JEAN</FirstName>
                    <MiddleName></MiddleName>
                    <LastName>SMITH</LastName>
                    <Gender>M</Gender>
                    <DateOfBirth>08/15/1983</DateOfBirth>
                    <PassportNumber>9DUSIJH232</PassportNumber>
                    <Nationality>CA</Nationality>
                    <CountryOfIssue>CA</CountryOfIssue>
                </ns2:PaxDetail>
            </ns2:ReadPNRResponse>
        </ns2:ReadPNRResponseBody>
    </soap:Body>
</soap:Envelope>

I want to loop on PaxDetail elements. I tried this but it looks like it's taking only the first element. How can I loop on PaxDetail

$response = $simpleXmlElement->children('soap', true)->Body->children('ns2', true);

foreach($response->ReadPNRResponseBody->ReadPNRResponse->PaxDetail->children() as $PaxDetail){

};

Solution

  • You are referencing the lowest level of data (<PaxRef> etc) in the foreach(), this should be done inside the loop so that the loop just loops over the <ns2:PaxDetail> elements...

    foreach($response->ReadPNRResponseBody->ReadPNRResponse->PaxDetail as $PaxDetail){
        echo $PaxDetail->children()->FirstName.PHP_EOL;
    };