Search code examples
phpjsonsoapsoapserver

Returning a JSON object from PHP SoapServer


How can I force my PHP SoapServer to send a JSON object as a response instead of an XML doc?

Thanks.


Solution

  • That is not SOAP, so no. It can incorporate a jsonstring in some xml node, that's about it. You may want just a REST server serving json.

    You can bastardize it though, making it by definition NOT SOAP, but some weird hybrid:

    <?php
    class ThisIsNotASoapServer extends SoapServer {
    
    }
    function test(){
            //should have a return
            //return range(1,9);
            //but totally breaks it by:
            echo json_encode(range(1,9));
            //the exit here is needed
            exit;
    }
    $server = new ThisIsNotASoapServer(null, array('uri' => 'http://test-uri/','soap_version' => 1));
    $server->addFunction("test");
    $server->handle('<?xml version="1.0"?>
    <SOAP-ENV:Envelope
       xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
       SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        <SOAP-ENV:Body>
            <m:Test xmlns:m="Some-URI"/>
        </SOAP-ENV:Body>
     </SOAP-ENV:Envelope>');
    ?>
    

    ... so, technically this is possible, but I suspect there is not a single client which understands this.