【问题标题】:How to consume a response from a WCF REST web service with PHP如何使用 PHP 使用来自 WCF REST Web 服务的响应
【发布时间】:2011-08-25 23:43:26
【问题描述】:

我在 .net 中内置了 web 服务,看起来像这样:

[ServiceContract]
public interface IRestService
{
    [OperationContract]
    [WebGet(UriTemplate = "object/{name}")]
    Object GetObject(string name);
}

public class api : IRestService
{
    OSAE.OSAE osae = new OSAE.OSAE("WebService");

    public Object GetObject(string name)
    {
        // lookup object 
        OSAEObject OSAEobj = osae.GetObjectByName(name);
        Object obj = new Object();
        obj.Name = OSAEobj.Name;
        obj.Address = OSAEobj.Address;
        obj.Type = OSAEobj.Type;
        obj.Container = OSAEobj.Container;
        obj.Enabled = OSAEobj.Enabled;
        obj.Description = OSAEobj.Description;

        return obj;
    }
 }

当我只使用浏览器调用它时,这将给出如下所示的响应:

<Object xmlns="http://schemas.datacontract.org/2004/07/OSAERest" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Address/>
<Container>SYSTEM</Container>
<Description>Email</Description>
<Enabled>0</Enabled>
<Name>Email</Name>
<Properties xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" i:nil="true"/>
<Type>EMAIL</Type>
</Object>

我需要能够使用 PHP 来使用它。我尝试过使用 Pest (https://github.com/educoder/pest),但我什么也做不了。这是我的尝试:

<?php
require_once 'Includes/PestXML.php';
$pest = new PestXML('http://localhost:8732/api');
$things = $pest->get('/object/email');
$names = $things->xpath('//Object/Description');
while(list( , $node) = each($names)) {
    echo $node,"\n";
}
?>

如何使用 PHP 正确使用我的 Web 服务响应?

【问题讨论】:

    标签: php .net web-services rest


    【解决方案1】:

    将 WebGet 声明更改为以下内容:

    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "object/{name}")]
    

    然后您可以通过调用 json_decode($result) 来使用 PHP 中的响应。 (下例)

    $url = "http://localhost:8732/api/object/wibble";
    $response = file_get_contents($url);
    
    $jsonData = json_decode($response);
    
    var_dump($jsonData);
    

    如果您将“json_decode”第二个参数设置为 true,您将获得关联数组而不是对象图。

    【讨论】:

    • 使用 Pest 可能会更容易。更改 API 以提供 JSON 内容后,只需使用 PestJSON 而不是 PestXML。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多