首页 > 解决方案 > CakePHP 3.5:如何使用 php 将 xml 响应转换为应用程序响应

问题描述

我正在使用 CakePHP 框架并使用 HttpClient(cakephp) 获取响应。我尝试将 xml 转换为 php,但在使用此函数 SimpleXMLElement() 时它返回空对象

<soap:envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:body>
    <getaccountbalanceresponse xmlns="http://PegPayTelecomsApi/">
        <getaccountbalanceresult>
            <balance>xxx</balance>
            <statusdesc>xxxx</statusdesc>
            <statuscode>xxxx</statuscode>
        </getaccountbalanceresult>
    </getaccountbalanceresponse>
</soap:body>

如何将 xml 转换为 php。任何人都可以帮助我..

我的php代码是

$this->client = new Client();
    $this->response->statusCode(200);

    $this->RequestHeader = [
        'headers' => [
            'cache-control' => 'no-cache',
            'content-type' => 'text/xml',
        ],
        'ssl_verify_peer' => false,
        'ssl_verify_host' => false,
        'ssl_verify_peer_name' => false,
    ];

    $this->OAuthUrl = 'https://test.pegasus.co.ug:8019/pegpaytelecomsapi/PegPayTelecomsApi.asmx';


    $this->RequestAccessBody = '<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
    <GetAccountBalance xmlns="http://PegPayTelecomsApi/">
        <vendorcode>CCCCC</vendorcode>
        <password>RRRRRRR</password>
    </GetAccountBalance>
</Body>

';

    $response = $this->client->post($this->OAuthUrl,$this->RequestAccessBody,$this->RequestHeader);

    $soap    = simplexml_load_string($response->body);

标签: phpxmlcakephpxml-parsingxmlhttprequest

解决方案


$response = $this->client->post($this->OAuthUrl,$this->RequestAccessBody,$this->RequestHeader);

$soap = $response->xml; // xml response as array

debug($soap);

读:

https://book.cakephp.org/3/en/core-libraries/httpclient.html#reading-json-and-xml-response-bodies


推荐阅读