Finding API

Using Advanced Search
Specifying XML Results with an HTTP GET Request

Complete Code

This tutorial shows how to use the Finding API to perform complex searches. Specifically, you use PHP to write a keyword-based findItemsAdvanced GET request to search for eBay listings and display the results in three price ranges. You specify that the response to your call is formatted as XML, and that the browser displays the results in an HTML table.

If the links you present to users (after making these calls) include affiliate tracking information, as described in this tutorial, you can earn commissions from eBay. To get an affiliate tracking number, go to eBay Partner Network. For notes about the tutorial, please see Notes and Next Steps. For additional resources, please see Additional Resources.

When you complete the tutorial, you will have created an application that returns results like this:

Simple search code

The keyword "ipod" returns items in three bands (the three price ranges specified in the request) that map neatly to different types of Ipods at different price levels.

The first band, the cheapest price range, tends to capture accessories and Ipod nanos. The second band, the middle price range, tends to return mid-range Ipods. The third band tends to return top-drawer Ipods with generous storage capacity and special features.

If the three-price-range search were applied to a book search, an author's name might return items in a similar array: cheap editions in the first range, hardcovers in good condition in the second, and in the third collectible-quality items such as first editions and signed copies.

This kind of search can give a snapshot to market price patterns for items that can be grouped by keywords.

There are two main steps in this tutorial:

Step 1: Set up the findItemsAdvanced call

Step 2: Add code to make the call and display the response

Step 3: Run the code

The code you write in this tutorial is included in the file FindItemsAdvanced.php, which is contained in PHP_SearchInterm_NV_XML.zip, along with the auxiliary files used by the application, which include display functions and the jQuery JavaScript library. The search returns live production data.


Prerequisites

  1. Please join the eBay Developers Program. Note the Production AppID that you receive when you join. It is required to make Shopping API calls. Substitute your Production AppID in this tutorial where the code says "MyAppID." Note that your Production AppID is not the same as your eBay user ID.
  2. Please install Apache HTTP Server.
  3. Please install PHP 5. PHP 5 includes the SimpleXML extension. The PHP sample file you download with this tutorial will be stored in the htdocs folder of your Apache 2.2 installation (such as C:\Program Files\Apache Software Foundation\Apache2.2\htdocs).

Step 1: Set up the findItemsAdvanced call

In this step, you put two folders and one file into your htdocs folder. You also create your main PHP file and add some text to create the HTML that will display in the browser of a user of this application.

  1. Copy two folders and one file to htdocs. After you download the complete code in PHP_SearchInterm_NV_XML.zip, copy the js and css folders to the htdocs folder of your Apache 2.2 installation (say, C:\Program Files\Apache Software Foundation\Apache2.2\htdocs).
  2. Create a file with the following text.
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>findItemsAdvanced</title>
    <script src="./js/jQuery.js"></script>
    <script src="./js/jQueryUI/ui.tablesorter.js"></script>
    
    <script>
        $(document).ready(function() {
            $("table").tablesorter({
                sortList:[[7,0],[4,0]],      // upon screen load, sort by col 7, 4 ascending (0)
                debug: false,                // if true, useful to debug Tablesorter issues
                headers: {
                    0: { sorter: false },    // col 0 = first = left most column - no sorting
                    5: { sorter: false },
                    6: { sorter: false },
                    7: { sorter: 'text'}     // specify text sorter, otherwise mistakenly takes shortDate parser
                }
            });
        });
    </script>
    
    
    
    </head>
    <body>
    
    
    <link rel="stylesheet" href="./css/flora.all.css" type="text/css" media="screen" title="Flora (Default)">
    
    <form action="FindItemsAdvanced.php" method="post">
    <table cellpadding="2" border="0">
      <tr>
        <th>Query</th>
        <th>Site to Search</th>
        <th>Max Price</th>
        <th>Items per range</th>
        <th>Debug</th>
      </tr>
      <tr>
        <td><input type="text" name="Query" value="ipod"></td>
        <td>
        <select name="GlobalID">
          <option value="EBAY-AU">Australia - EBAY-AU - AUD</option>
          <option value="EBAY-ENCA">Canada (English) - EBAY-ENCA - CAD</option>
          <option value="EBAY-DE">Germany - EBAY-DE - EUR</option>
          <option value="EBAY-GB">United Kingdom - EBAY-GB - GBP</option>
          <option value="EBAY-US">United States - EBAY-US - USD</option>
          </select>
        </td>
        <td><input type="text" name="MaxPrice" value="500"></td>
        <td>
        <select name="ItemsPerRange">
          <option value="1">1</option>
          <option value="2">2</option>
          <option selected value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          </select>
        </td>
        <td>
        <select name="Debug">
          <option value="1">true</option>
          <option selected value="0">false</option>
          </select>
        </td>
      </tr>
      <tr>
        <td colspan="2" align="center"><INPUT type="submit" name="submit" value="Search">
        </td>
      </tr>
    </table>
    </form>
    
  3. Save as FindItemsAdvanced.php in the htdocs folder of your Apache 2.2 installation.

  4. Review the values you will use in your call. The following table contains the values you will use for your findItemsAdvanced call.

  5. Affiliate information.
    Standard Parameter     Sample Value Description
    appid MyAppID The appid you obtain by joining the eBay Developers Program.
    version537The API version that your application supports.
    siteid 0 The numeric value for the eBay site with the items you want information about. The site ID of the US site is 0.
    callname findItemsAdvanced The name of the call you are using.
    responseencoding XML Specifies an encoding format for the response.
    QueryKeywordsipodSearch terms.
    ItemSortBestMatch
    IncludeSelectorSearchDetails
    trackingpartnercode1
    trackingid123Affiliate information.
    affiliateuserid456Affiliate information.

    Call-Specific Value Sample Value Description
    QueryKeywords ipod Specifies a search string.
    MaxEntries 6 Integer that specifies maximum number of items to return.
    ItemSort BestMatch A value that sets the sort order of the results.
    ItemType FixedPricedItem Item filter based on type of listing.
    PriceMin.Value and PriceMax.Value0 and 500Defines the overall price range.

  6. Add the following PHP function to your code, directly after </form>. This function will construct your FindItemsAdvanced call. This is where you specify the values for the site, the response encoding, the type of query, the site ID, the maximum number of entries in the return, and the price ranges.
  7. 
    <?php
    
    require_once('DisplayUtils.php');  // functions to aid with display of information
    
    error_reporting(E_ALL);  // turn on all errors, warnings and notices for easier debugging
    
    $results = '';
    
    if(isset($_POST['Query']))
    {
    
      $endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';  // URL to call
      $responseEncoding = 'XML';   // Format of the response
    
      $safeQuery = urlencode (utf8_encode($_POST['Query']));
      $site  = $_POST['GlobalID'];
    
      $priceRangeMin = 0.0;
      $priceRangeMax = $_POST['MaxPrice'];
      $itemsPerRange = $_POST['ItemsPerRange'];
      $debug = (boolean) $_POST['Debug'];
    
      $rangeArr = array('Low-Range', 'Mid-Range', 'High-Range');
    
      $priceRange = ($priceRangeMax - $priceRangeMin) / 3;  // find price ranges for three tables
      $priceRangeMin =  sprintf("%01.2f", 0.00);
      $priceRangeMax = $priceRangeMin;  // needed for initial setup
    
      foreach ($rangeArr as $range)
      {
        $priceRangeMax = sprintf("%01.2f", ($priceRangeMin + $priceRange));
        $results .=  "<h2>$range : $priceRangeMin ~ $priceRangeMax</h2>";
        // Construct the FindItems call
        $apicall = "$endpoint?OPERATION-NAME=findItemsAdvanced"
             . "&SERVICE-VERSION=1.0.0"
             . "&GLOBAL-ID=$site"
             . "&SECURITY-APPNAME=YOUR_APP_ID"
             . "&keywords=$safeQuery"
             . "&paginationInput.entriesPerPage=$itemsPerRange"
             . "&sortOrder=BestMatch"
             . "&itemFilter(0).name=ListingType"
             . "&itemFilter(0).value=FixedPrice"
             . "&itemFilter(1).name=MinPrice"
             . "&itemFilter(1).value=$priceRangeMin"
             . "&itemFilter(2).name=MaxPrice"
             . "&itemFilter(2).value=$priceRangeMax"
             . "&affiliate.networkId=9"  // fill in your information in next 3 lines
             . "&affiliate.trackingId=1234567890"
             . "&affiliate.customId=456"
             . "&RESPONSE-DATA-FORMAT=$responseEncoding";
    
        if ($debug) {
          print "GET call = $apicall <br>";  // see GET request generated
        }
    	


    Back to Top

    Step 2: Add code to load the call and display the response

    In this step you:

    • Add code to make the call
    • Add code and a helper file to display the items returned.

    As described in Step 1, the URL used for the Shopping API call in this tutorial is http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsAdvanced&SERVICE-VERSION=1.0.0&GLOBAL-ID=EBAY-AU&SECURITY-APPNAME=YOUR_APP_ID&keywords=ipod&paginationInput.entriesPerPage=3&sortOrder=BestMatch&itemFilter(0).name=ListingType&itemFilter(0).value=FixedPrice&itemFilter(1).name=MinPrice&itemFilter(1).value=0.00&itemFilter(2).name=MaxPrice&itemFilter(2).value=166.67&affiliate.networkId=9&affiliate.trackingId=1234567890&affiliate.customId=456&RESPONSE-DATA-FORMAT=XML.

    The responseencoding=XML parameter specifies that the response data will be in XML format.

    1. In FindItemsAdvanced.php, after the last line above (where $endpoint is set to a URL value), add the following code:

      Add the code that constructs the layout of the FindItemsAdvanced call and specifies the results to display.

          // Load the call and capture the document returned by the Finding API
          $resp = simplexml_load_file($apicall);
      
          // Check to see if the response was loaded, else print an error
          // Probably best to split into two different tests, but have as one for brevity
          if ($resp && $resp->paginationOutput->totalEntries > 0) {
            $results .= 'Total items : ' . $resp->paginationOutput->totalEntries . "<br />";
            $results .= '<table id="example" class="tablesorter" border="0" cellpadding="0" cellspacing="1">';
            $results .= "<thead><tr><th /><th>Title</th><th>Price     </th><th>Shipping     </th><th>Total     </th><th><!--Currency--></th><th>Time Left</th><th>End Time</th></tr></thead>";
      
            // If the response was loaded, parse it and build links
            foreach($resp->searchResult->item as $item) {
              if ($item->galleryURL) {
                $picURL = $item->galleryURL;
              } else {
                $picURL = "http://pics.ebaystatic.com/aw/pics/express/icons/iconPlaceholder_96x96.gif";
              }
              $link  = $item->viewItemURL;
              $title = $item->title;
      
              $price = sprintf("%01.2f", $item->sellingStatus->convertedCurrentPrice);
              $ship  = sprintf("%01.2f", $item->shippingInfo->shippingServiceCost);
              $total = sprintf("%01.2f", ((float)$item->sellingStatus->convertedCurrentPrice
                            + (float)$item->shippingInfo->shippingServiceCost));
      
              // Determine currency to display - so far only seen cases where priceCurr = shipCurr, but may be others
              $priceCurr = (string) $item->sellingStatus->convertedCurrentPrice['currencyId'];
              $shipCurr  = (string) $item->shippingInfo->shippingServiceCost['currencyId'];
              if ($priceCurr == $shipCurr) {
                $curr = $priceCurr;
              } else {
                $curr = "$priceCurr / $shipCurr";  // potential case where price/ship currencies differ
              }
      
              $timeLeft = getPrettyTimeFromEbayTime($item->sellingStatus->timeLeft);
              $endTime = strtotime($item->listingInfo->endTime);   // returns Epoch seconds
              $endTime = $item->listingInfo->endTime;
      
      
              $results .= "<tr><td><a href=\"$link\"><img src=\"$picURL\"></a></td><td><a href=\"$link\">$title</a></td>"
                   .  "<td>$price</td><td>$ship</td><td>$total</td><td>$curr</td><td>$timeLeft</td><td><nobr>$endTime</nobr></td></tr>";
            }
            $results .= "</table>";
          }
          // If there was no response, print an error
          else {
            $results = "<p><i><b>No items found<b></i></p>";
          }
          $priceRangeMin = $priceRangeMax; // set up for next iteration
        } // foreach
      
      } // if
      
      
      ?>
      
      
      <?php echo $results;?>
      </body>
      </html>
      
      
      
    2. Add an auxiliary PHP file to improve display.
    3. Create (or copy from the PHP_SearchInterm_NV_XML.zip file) a separate file named DisplayUtils.php. This file contains a pair of convenience functions that prettify the display of the results. The functions are not needed to make the FindItemsAdvanced call. The DisplayUtils.php file is "required" in FindItemsAdvanced.php merely to access the convenience functions.

      <?php
      
      date_default_timezone_set('GMT');
      
      function getPrettyTimeFromEbayTime($eBayTimeString){
          // Input is of form 'PT12M25S'
          $matchAry = array(); // initialize array which will be filled in preg_match
          $pattern = "#P([0-9]{0,3}D)?T([0-9]?[0-9]H)?([0-9]?[0-9]M)?([0-9]?[0-9]S)#msiU";
          preg_match($pattern, $eBayTimeString, $matchAry);
      
          $days  = (int) $matchAry[1];
          $hours = (int) $matchAry[2];
          $min   = (int) $matchAry[3];    // $matchAry[3] is of form 55M - cast to int
          $sec   = (int) $matchAry[4];
      
          $retnStr = '';
          if ($days)  { $retnStr .= "$days day"    . pluralS($days);  }
          if ($hours) { $retnStr .= " $hours hour" . pluralS($hours); }
          if ($min)   { $retnStr .= " $min minute" . pluralS($min);   }
          if ($sec)   { $retnStr .= " $sec second" . pluralS($sec);   }
      
          return $retnStr;
      } // function
      
      function pluralS($intIn) {
          // if $intIn > 1 return an 's', else return null string
          if ($intIn > 1) {
              return 's';
          } else {
              return '';
          }
      } // function
      
      ?>
      
      
      
    4. Save the DisplayUtils.php file in the htdocs folder of your Apache 2.2 installation.


    Back to Top

    Step 3: Run the code

    The FindItemsAdvanced.php file is complete. Open the file in a browser (http://localhost/FindItemsAdvanced.php).

    The result should look similar to the following:

    Simple search code

    Congratulations! You have used the Shopping API to find items on eBay and to display the results to a user.

    For information about the business benefits of using the eBay Developers Program and for other important information, please see the Quick Start Guide.


    Back to Top


    Notes and Next Steps

    Try different input parameters to change the search criteria, or modify the application to display additional fields.

    Exercise 1: Search for "Transformers."

    Exercise 2: Add an Endtime filter.

    eBay Partner Network (eBay Affiliate Program)

    You may be able to earn money with the eBay Partner Network (eBay Affiliate Program). For more information, visit the eBay Partner Network. This tutorial contains affiliate-related code. The code is commented-out because affiliate functionality is not available in the Sandbox environment.

    For information about the URL parameters for affiliate tracking, see the Affiliate URL Parameters and HTTP Header Values table.

    Troubleshooting

    If your code does not run, just use the FindItemsAdvanced.php file in PHP_SearchInterm_NV_XML.zip.

    About the Application

    The sample provided with this tutorial was built and tested on a Windows 2000 Server platform using PHP 5.2.1 for Win32 and Apache 2.2.4 for Windows.

    About the Call

    See findItemsAdvanced in the API Reference for descriptions of the input and output parameters and additional information.


    Back to Top


    Additional Resources

    More information about the Finding API is available at these locations:

    API Reference

    User Guide

    Making a Call

    Copyright © 2009–2016 eBay, Inc. All rights reserved. This documentation and the API may only be used in accordance with the eBay Developers Program and API License Agreement.