Vineet
Vineet

Reputation: 4655

how to get xml node value php

I've fired a curl request. My code is

$URL = "http://demo.com";

            $ch = curl_init($URL);
            curl_setopt($ch, CURLOPT_MUTE, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, "$xmlLeadCloud");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);

            curl_close($ch);

Below I am getting the XML in $output variable.

<?xml version="1.0" encoding="utf-16"?>
<LeadCloud>
    <InsuranceSvcRs>
        <PersHealthPolicyQuoteInqRs>
            <MsgStatus>
                <MsgStatusCd>Success</MsgStatusCd>
                <Payout>17.40</Payout>
                <BuyerLeadId>4ded4da790c6fasasasas322</BuyerLeadId>
                <BuyerId>34</BuyerId>
            </MsgStatus>
        </PersHealthPolicyQuoteInqRs>
    </InsuranceSvcRs>
</LeadCloud>

How could I get MsgStatusCd element's value from it. So far I've tried.

$s = new SimpleXMLElement($output);
echo $s->InsuranceSvcRs->PersHealthPolicyQuoteInqRs->MsgStatus->MsgStatusCd; die; //not working

Upvotes: 1

Views: 76

Answers (2)

Matiss
Matiss

Reputation: 341

You can use XPath to access this data (see PHP manual entry).

The reason why your accessor does not work is that the XML you are receiving is a data array, hence,

<?xml version="1.0" encoding="utf-16"?>
<LeadCloud> <!-- ROOT -->
    <InsuranceSvcRs> <!-- Zero or more -->
        <PersHealthPolicyQuoteInqRs> <!-- Zero or more -->
            <MsgStatus> <!-- Zero or more -->
                <MsgStatusCd>Success</MsgStatusCd> <!-- Zero or one -->
                <Payout>17.40</Payout> <!-- Zero or one -->
                <BuyerLeadId>4ded4da790c6fasasasas322</BuyerLeadId> <!-- Zero or one -->
                <BuyerId>34</BuyerId> <!-- Zero or one -->
            </MsgStatus>
        </PersHealthPolicyQuoteInqRs>
    </InsuranceSvcRs>
</LeadCloud>

and should be accessed as such.

Upvotes: 0

nickb
nickb

Reputation: 59709

Cast the output to a string to get its value:

echo (string) $xml->InsuranceSvcRs->PersHealthPolicyQuoteInqRs->MsgStatus->MsgStatusCd;

You can see from this demo where it prints:

Success

Upvotes: 2

Related Questions