我想转换soap xml响应并将其存储在数据库中。这是我的XML文件。
<ENV:Envelope xmlns:ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/soap/example">
<ENV:Body>
<ns1:GetCentresResponse>
<ExampleCentre>
<ns1:Cent>
<ID>200</ID>
<Name>example2</Name>
<Code>ex2</Code>
<Email>example2@example2.com</Email>
<Address1>example2, example2 </Address1>
<Address2>example2, example2 </Address2>
<City>example2</City>
<PostCode>111111</PostCode>
<Telephone>1111111111</Telephone>
<Location>11.11,-11.11</Location>
<URL>/example2/exam2/ex2</URL>
</ns1:Cent>
</ExampleCentre>
</ns1:GetCentresResponse>
</ENV:Body>
</ENV:Envelope>
我从服务器得到这个soap响应。我想把它转换成数组并存储在数据库中。我该怎么办?我知道答案可能很直接,但是嘿,我是一个新手:D
我将非常感谢任何帮助我得到。
衷心感谢。
对
最好的解决方案是使用PHP的SoapClient类来执行调用,它将返回一个对象,然后将该对象转换为数组,如下所示:
<?php
$client = new SoapClient("http://localhost/code/soap.wsdl");
// Soap call with HelloWorld() method
$something = $client->HelloWorld(array('option1' => 'attribute1'));
// Convert object to array
$array = (array)$something;
?>
如果您不能使用SoapClient
来检索PHP对象中的SOAP响应,那么使用SimpleXML来解析SOAP响应。
例如(其中$xmlstr
包含SOAP响应):
$element = new SimpleXMLElement( $xmlstr );
$centerElement = $element->Body->GetCentresResponse->ExampleCentre->Cent;
$center = array(
$centerElement->ID,
$centerElement->Name,
$centerElement->Code,
$centerElement->Email,
$centerElement->Address1,
$centerElement->Address2,
$centerElement->City,
$centerElement->PostCode,
$centerElement->Telephone,
$centerElement->Location,
$centerElement->URL,
);
现在可以在数据库中存储$center
了
使用以下代码解析SOAP对数组的响应:
您只需要使用SOAP-XML调用函数。之后,它将返回一个纯XML,然后您必须使用JSON编码解码将其转换为数组。
$plainXML = mungXML($soapXML);
$arrayResult = json_decode(json_encode(SimpleXML_Load_String($plainXML, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
// FUNCTION TO MUNG THE XML SO WE DO NOT HAVE TO DEAL WITH NAMESPACE
function mungXML($xml)
{
$obj = SimpleXML_Load_String($xml);
if ($obj === FALSE) return $xml;
// GET NAMESPACES, IF ANY
$nss = $obj->getNamespaces(TRUE);
if (empty($nss)) return $xml;
// CHANGE ns: INTO ns_
$nsm = array_keys($nss);
foreach ($nsm as $key)
{
// A REGULAR EXPRESSION TO MUNG THE XML
$rgx
= '#' // REGEX DELIMITER
. '(' // GROUP PATTERN 1
. ''<' // LOCATE A LEFT WICKET
. '/?' // MAYBE FOLLOWED BY A SLASH
. preg_quote($key) // THE NAMESPACE
. ')' // END GROUP PATTERN
. '(' // GROUP PATTERN 2
. ':{1}' // A COLON (EXACTLY ONE)
. ')' // END GROUP PATTERN
. '#' // REGEX DELIMITER
;
// INSERT THE UNDERSCORE INTO THE TAG NAME
$rep
= '$1' // BACKREFERENCE TO GROUP 1
. '_' // LITERAL UNDERSCORE IN PLACE OF GROUP 2
;
// PERFORM THE REPLACEMENT
$xml = preg_replace($rgx, $rep, $xml);
}
return $xml;
}
print_r($arrayResult);