dongzuo9096 2016-05-26 12:47
浏览 71
已采纳

为什么我的simplexml_load_string不允许我在php变量中存储xml属性?

I have a php variable ($output) that is holding a xml file with the following attributes

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="tns:ns">
<SOAP-ENV:Body><ns1:transactionStatusResponse>
<MSISDN>254705680609</MSISDN>
<AMOUNT>10</AMOUNT>
<MPESA_TRX_DATE>2016-05-21 10:57:43</MPESA_TRX_DATE>
<MPESA_TRX_ID>KEL7STGYEL</MPESA_TRX_ID>
<TRX_STATUS>Success</TRX_STATUS>
<RETURN_CODE>00</RETURN_CODE>
<DESCRIPTION>The service request is processed successfully.</DESCRIPTION>
<MERCHANT_TRANSACTION_ID/>
<ENC_PARAMS></ENC_PARAMS>
<TRX_ID>308e6137d9888ee8ead15c9577802947</TRX_ID>
</ns1:transactionStatusResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Now I am trying to put the individual xml attributes into php varibles but I seems not to be working. This is the what I am trying to use to extract the individual attributes

$xml = @simplexml_load_string($output);
$MPESA_TRX_ID= (string)$xml->MPESA_TRX_ID; 
$MSISDN = (string)$xml->MSISDN;
$AMOUNT = (string)$xml->AMOUNT;

Any workarounds this?

  • 写回答

1条回答 默认 最新

  • dongziche8030 2016-05-26 13:18
    关注

    Here's a way how you can treat the xml from your question

    $xml = @simplexml_load_string($output);
    $xml->registerXPathNamespace("soap","http://schemas.xmlsoap.org/soap/envelope/");
    $xml->registerXPathNamespace("ns1","tns:ns");
    
    $xml2 = $xml->xpath("//soap:Envelope/soap:Body/ns1:transactionStatusResponse");
    /*
    foreach($xml2 as $item){
        var_dump($item->getName());
        browse($item);
        echo "
    ";
    }
    
    function browse($elem)
    {
        if($elem->children())
        {
            foreach($elem->children() as $child)
            {
                var_dump($child->getName());
                browse($child);
            }
        }
    }
    
    exit();
    */
    
    $MPESA_TRX_ID = (string) $xml2[0]->MPESA_TRX_ID;
    $MSISDN       = (string) $xml2[0]->MSISDN;
    $AMOUNT       = (string) $xml2[0]->AMOUNT;
    
    var_dump($MPESA_TRX_ID);
    echo "
    ";
    var_dump($MSISDN);
    echo "
    ";
    var_dump($AMOUNT);
    

    output:

    string(10) "KEL7STGYEL"
    
    string(12) "254705680609"
    
    string(2) "10"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘