如何获取xml节点值php

时间:2015-07-20 15:40:39

标签: php xml

我发了一个卷毛请求。我的代码是

$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);

下面我在$output变量中获取XML。

<?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>

我怎样才能从中获取MsgStatusCd元素的值。到目前为止,我已经尝试过了。

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

2 个答案:

答案 0 :(得分:2)

将输出转换为字符串以获取其值:

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

您可以在this demo处看到它打印的位置:

Success

答案 1 :(得分:0)

您可以使用XPath访问此数据(请参阅PHP manual条目)。

您的访问者无法工作的原因是您收到的XML是数据数组,因此,

<?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>

,应该这样访问。