2

I am very new to PHP. I wanted to call restful api in PHP. I am doing same in jQuery as below

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) {

                });
            }
        });

How can I do same in PHP. I have two difficulties. First in URL there is $ sign which PHP assume as variable and other I don't know how to do that

Milind
  • 1,855
  • 5
  • 30
  • 71

2 Answers2

13

Using curl for sending HTTP request.

<?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);
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
  • Thank you for reply but there is small issue $select and $filter in URL php think as variable. How can we overcome that – Milind Mar 20 '17 at 07:34
  • @Milind I have udpated my post you can check it now. I have changed URL variable in (`'`) single quotes. which will take it as a string rather than a variable – Sahil Gulati Mar 20 '17 at 07:36
  • It did not work as URL itself has single quote for Stations – Milind Mar 20 '17 at 07:52
  • @Milind Oops i forgot to escape single quotes.. I have updated my post now check – Sahil Gulati Mar 20 '17 at 07:56
  • @Milind can you provide me the exact url you want to hit – Sahil Gulati Mar 20 '17 at 08:51
  • This is exact URL https://www.kuwaitairways.com/_api/web/lists/getbytitle('Stations')/items?$select=OfficeId&$filter=CityCode eq 'KWI'' – Milind Mar 20 '17 at 08:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/138503/discussion-between-milind-and-sahil-gulati). – Milind Mar 20 '17 at 08:56
1

Hope this will help you.

$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);

Check below code for fetching d:OfficeId node value

$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;
    }   
}
Vara Prasad
  • 497
  • 3
  • 11