在PHP/nusoap中如何返回更复杂的数据类型?
在PHP/nusoap中如何返回更复杂的数据类型?
嘿,刚好之前用nusoap做API的时候折腾过复杂数据返回的事儿,给你唠唠靠谱的做法~
nusoap要返回复杂数据(比如包含数组的结构体、嵌套类型),核心是先提前定义好对应的复杂数据类型,再把组装好的数据返回就行,不然序列化的时候容易出问题,客户端也解析不了。我拿你提到的发票数据举个例子:
第一步:创建服务器并定义复杂类型
首先得把发票行、发票主数据这些复杂结构的类型给nusoap声明清楚:
// 初始化nusoap服务器 $server = new nusoap_server(); $server->configureWSDL('InvoiceAPI', 'urn:InvoiceAPI'); // 先定义单个发票行的结构 $server->wsdl->addComplexType( 'InvoiceLine', 'complexType', 'struct', 'all', '', array( 'line' => array('name' => 'line', 'type' => 'xsd:int'), 'item' => array('name' => 'item', 'type' => 'xsd:string'), 'quantity' => array('name' => 'quantity', 'type' => 'xsd:int'), 'unitPrice' => array('name' => 'unitPrice', 'type' => 'xsd:float') ) ); // 定义发票行的数组类型(因为发票里包含多个行) $server->wsdl->addComplexType( 'ArrayOfInvoiceLine', 'complexType', 'array', '', 'SOAP-ENC:Array', array(), array( array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:InvoiceLine[]') ), 'tns:InvoiceLine' ); // 最后定义完整的发票结构体,里面包含发票行数组 $server->wsdl->addComplexType( 'Invoice', 'complexType', 'struct', 'all', '', array( 'number' => array('name' => 'number', 'type' => 'xsd:int'), 'date' => array('name' => 'date', 'type' => 'xsd:string'), 'customer' => array('name' => 'customer', 'type' => 'xsd:string'), 'items' => array('name' => 'items', 'type' => 'xsd:int'), 'subtotal' => array('name' => 'subtotal', 'type' => 'xsd:float'), 'tax' => array('name' => 'tax', 'type' => 'xsd:float'), 'total' => array('name' => 'total', 'type' => 'xsd:float'), 'lines' => array('name' => 'lines', 'type' => 'tns:ArrayOfInvoiceLine') ) );
第二步:注册API方法并指定返回类型
把你的接口方法注册到nusoap里,明确告诉它返回的是我们刚才定义的Invoice类型:
$server->register( 'getInvoice', // 你的API方法名 array(), // 这里是输入参数,比如需要发票号的话可以加array('invoiceNum' => 'xsd:int') array('return' => 'tns:Invoice'), // 指定返回类型为我们定义的发票结构体 'urn:InvoiceAPI', 'urn:InvoiceAPI#getInvoice', 'rpc', 'encoded', '返回发票的完整信息,包含所有发票行' // 接口描述 );
第三步:实现方法并返回组装好的数据
现在就可以在方法里组装你需要的复杂数据,直接返回就行,nusoap会自动按照我们定义的类型序列化:
function getInvoice() { // 先组装发票行数据 $aInvoiceLines = array( array('line' => 1, 'item' => '办公笔记本', 'quantity' => 2, 'unitPrice' => 3.50), array('line' => 2, 'item' => '中性笔', 'quantity' => 5, 'unitPrice' => 0.60) ); // 组装完整发票数据 $aInvoice = array( 'number' => 100, 'date' => '20250425', 'customer' => 'cash', 'items' => 7, 'subtotal' => 10.00, 'tax' => 1.50, 'total' => 11.50, 'lines' => $aInvoiceLines ); return $aInvoice; }
几个要注意的小细节
- 类型一定要对应准确:比如整数用
xsd:int,浮点数用xsd:float,字符串用xsd:string,别搞混,不然序列化会出错。 - 如果要返回多个发票(也就是发票数组),那你还得再定义一个
ArrayOfInvoice的类型,和ArrayOfInvoiceLine的定义逻辑一样。 - 别忘了最后要处理请求和输出:
// 处理客户端请求 $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ''; $server->service($HTTP_RAW_POST_DATA); exit();
备注:内容来源于stack exchange,提问作者Paul Russell
相关产品推荐
相关产品推荐

