【问题标题】:Restful call in PHPPHP中的宁静调用
【发布时间】:2017-03-20 07:28:25
【问题描述】:

我对 PHP 很陌生。我想在 PHP 中调用 restful api。我在 jQuery 中做同样的事情,如下所示

var url;
url = "https://www.example.com/_api/lists/getbytitle('Stations')/items?$select=CityCode,CityNameEN&$filter=Active eq 'Yes'&$orderby=CityNameEN";
        $.ajax({
            url: url,
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            async: false,
            success: function (data) {
                $.each(data.d.results, function (i, item) {

                });
            }
        });

我怎样才能在 PHP 中做同样的事情。我有两个困难。首先在 URL 中有 $ 符号,PHP 假定它是变量,其他我不知道该怎么做

【问题讨论】:

标签: php jquery restful-url


【解决方案1】:

使用 curl 发送 HTTP 请求。

<?php
$url='https://www.kuwaitairways.com/_api/web/lists/getbytitle(\'Stations\')/items?$select=OfficeId&$filter=CityCode%20eq%20%27KWI%27';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/xml"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $result = curl_exec($ch);

【讨论】:

  • 感谢您的回复,但 URL php 中的 $select 和 $filter 认为是变量存在小问题。我们如何克服这一点
  • @Milind 我已经更新了我的帖子,您现在可以查看。我在 (') 单引号中更改了 URL 变量。它将把它作为一个字符串而不是一个变量
  • 它不起作用,因为 URL 本身对 Stations 有单引号
  • @Milind 哎呀我忘了转义单引号。我已经更新了我的帖子现在检查
  • @Milind 你能提供我你想点击的确切网址吗
【解决方案2】:

希望这会对你有所帮助。

$url="https://www.kuwaitairways.com/_api/web/lists/getbytitle('Stations')/items?";
$url .= "\$select=OfficeId&\$filter=".urlencode("CityCode eq 'KWI'");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/xml"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $result = curl_exec($ch);

检查下面的代码以获取 d:OfficeId 节点值

$office_id = "";
$xml=new DOMDocument;
$xml->loadXML($result);
$content_node = $xml->getElementsByTagName('content')->item(0);
foreach ($content_node->childNodes as $properties_node) {
    foreach ($properties_node->childNodes as $office_node) {
        $office_id = $office_node->nodeValue;
    }   
}

【讨论】:

  • 支持 urlencode 帮助我制作干净的动态 URL
  • 我只是在尝试搜索输出 XML。我该怎么做?
  • 您可以使用内置提供的 php xml 解析器函数。检查这个例子w3schools.com/php/…
  • 在 PHP 中没有简单的方法来搜索特定的标签值
  • 您想获取 d:OfficeId 值吗?在这种情况下,如果您获得多个或仅固定一个怎么办?
猜你喜欢
  • 1970-01-01
  • 2015-01-07
  • 2017-11-23
  • 2011-07-21
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
  • 2019-08-27
相关资源
最近更新 更多