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

时间:2016-05-26 12:47:45

标签: php xml xml-parsing xmlhttprequest

我有一个php变量($ output),它包含一个带有以下属性的xml文件

<div class="foto-item" ng-style="{'background-image':'url('+foto.path+')'}">
    <img class="materialboxed" ng-class="foto.picid" ng-src="{{foto.path}}" style="opacity: 0;filter: alpha(opacity=0);" width="100%" onclick="$('.materialboxed')/>
 </div>
<style>
.foto-item {
height: 75% !important;
width: 100%;
position: absolute;
top: 0;
left: 0;
overflow:hidden;
background-size: cover;
background-position: center center;
}
</style>

现在我试图将各个xml属性放入php varibles,但我似乎没有工作。这就是我试图用来提取个别属性

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

有任何解决方法吗?

1 个答案:

答案 0 :(得分:1)

以下是一种如何处理问题中的xml的方法

$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 "\n";
}

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 "\n";
var_dump($MSISDN);
echo "\n";
var_dump($AMOUNT);

输出:

string(10) "KEL7STGYEL"

string(12) "254705680609"

string(2) "10"