0

今天,我使用“Nusoap”库创建了一个带有 SOAP 的简单 WebServices 服务器。响应数据当然是 XML 格式。

我的服务器代码:

<?php
require_once "nusoap.php";

function pLogin($username, $password) {
    if (($username == "admin")&&($password == md5("123456"))) {
        //return "AAAAAAAAAA Login OK";
        return (array("cmd" => "LOGIN","status" => "LOGINOK","fullname" => "John Smith", "phone" => "0987654321", "credit" => "5600", "session" => "ID24324343434"));
    }
    else {
            return "Login Fail";
    }
}

$server = new soap_server();
$server->register("pLogin");
$server->service($HTTP_RAW_POST_DATA);
?>

HTTP响应为:

<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" 
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
    <SOAP-ENV:Body>
        <ns1:pLoginResponse xmlns:ns1="http://tempuri.org">
            <return>
                <cmd xsi:type="xsd:string">LOGIN</cmd>
                <status xsi:type="xsd:string">LOGINOK</status>
                <fullname xsi:type="xsd:string">John Smith</fullname>
                <phone xsi:type="xsd:string">0987654321</phone>
                <credit xsi:type="xsd:string">5600</credit>
                <session xsi:type="xsd:string">ID24324343434</session>
            </return>
        </ns1:pLoginResponse>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

但我想以 JSON 格式创建响应数据,例如 or :

HTTP/1.1 200 OK
.... (HTTP header here)
Content-Type: text/json
{"cmd":"LOGIN","status":"LOGINOK","fullname":"John Smith","phone":"0987654321","credit":"5600","session":"ID24324343434"}

请帮我修改 WebServices 服务器中的代码以创建 JSON 格式的数据。

4

1 回答 1

2

代替

return (array("cmd" => "LOGIN","status" => "LOGINOK","fullname" => "John Smith", "phone" => "0987654321", "credit" => "5600", "session" => "ID24324343434"));

return json_encode(array("cmd" => "LOGIN","status" => "LOGINOK","fullname" => "John Smith", "phone" => "0987654321", "credit" => "5600", "session" => "ID24324343434"));
于 2013-02-05T15:50:48.763 回答