Hello,

I'm hoping if someone could help me with this, I don't think it's to complicated but I'm still having some problems.

I have the following code which takes the keywords 'oxford' and 'oxfordshire' for $query and ultimately searches for items with these words in on eBay(UK). I have another copy of this file which searches for another location, and an output.php file which displays the results. At the moment this code works perfectly, but what I would like to do is have it take the child elements 'name' and 'region' from a config.xml file instead of hard coding the keywords in. I hope this makes sense.

PHP -

<?php
error_reporting(E_ALL);  // Turn on all errors, warnings, and notices for easier debugging

// API request variables
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';  // URL to call
$query = 'oxford, oxfordshire';  // Supply your own query keywords as needed

// Create a PHP array of the item filters you want to use in your request
$filterarray =
  array(
    array(
    'name' => 'MaxPrice',
    'value' => '25',
    'paramName' => 'Currency',
    'paramValue' => 'GBP'),
    array(
    'name' => 'FreeShippingOnly',
    'value' => 'true',
    'paramName' => '',
    'paramValue' => ''),
    array(
    'name' => 'ListingType',
    'value' => array('AuctionWithBIN','FixedPrice','StoreInventory'),
    'paramName' => '',
    'paramValue' => ''),
  );

// Generates an XML snippet from the array of item filters
function buildXMLFilter ($filterarray) {
  global $xmlfilter;
  // Iterate through each filter in the array
  foreach ($filterarray as $itemfilter) {
    $xmlfilter .= "<itemFilter>\n";
    // Iterate through each key in the filter
    foreach($itemfilter as $key => $value) {
      if(is_array($value)) {
        // If value is an array, iterate through each array value
        foreach($value as $arrayval) {
          $xmlfilter .= " <$key>$arrayval</$key>\n";
        }
      }
      else {
        if($value != "") {
          $xmlfilter .= " <$key>$value</$key>\n";
        }
      }
    }
    $xmlfilter .= "</itemFilter>\n";
  }
  return "$xmlfilter";
} // End of buildXMLFilter function

// Build the item filter XML code
buildXMLFilter($filterarray);

// Construct the findItemsByKeywords POST call
// Load the call and capture the response returned by the eBay API
// the constructCallAndGetResponse function is defined below
$resp = simplexml_load_string(constructPostCallAndGetResponse($endpoint, $query, $xmlfilter));

// Check to see if the call was successful, else print an error
if ($resp->ack == "Success") {
  $results = '';  // Initialize the $results variable

  // Parse the desired information from the response
  foreach($resp->searchResult->item as $item) {
    $pic   = $item->galleryURL;
    $link  = $item->viewItemURL;
    $title = $item->title;

    // Build the desired HTML code for each searchResult.item node and append it to $results
    $results .= "<tr><td><img src=\"$pic\"></td><td><a href=\"$link\">$title</a></td></tr>";
  }
}
else {  // If the response does not indicate 'Success,' print an error
  $results  = "<h3>Oops! The request was not successful. Make sure you are using a valid ";
  $results .= "AppID for the Production environment.</h3>";
}
?>

<!-- Build the HTML page with values from the call response -->
<html>
<head>
<title>eBay Search Results for <?php echo $query; ?></title>
<style type="text/css">body {font-family: arial, sans-serif;} </style>
</head>
<body>

<h1>eBay Search Results for <?php echo $query; ?></h1>

<table>
<tr>
  <td>
    <?php echo $results;?>
  </td>
</tr>
</table>

</body>
</html>

<?php
function constructPostCallAndGetResponse($endpoint, $query, $xmlfilter) {
  global $xmlrequest;

  // Create the XML request to be POSTed
  $xmlrequest  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  $xmlrequest .= "<findItemsByKeywordsRequest xmlns=\"http://www.ebay.com/marketplace/search/v1/services\">\n";
  $xmlrequest .= "<keywords>";
  $xmlrequest .= $query;
  $xmlrequest .= "</keywords>\n";
  $xmlrequest .= $xmlfilter;
  $xmlrequest .= "<paginationInput>\n <entriesPerPage>3</entriesPerPage>\n</paginationInput>\n";
  $xmlrequest .= "</findItemsByKeywordsRequest>";

  // Set up the HTTP headers
  $headers = array(
    'X-EBAY-SOA-OPERATION-NAME: findItemsByKeywords',
    'X-EBAY-SOA-SERVICE-VERSION: 1.3.0',
    'X-EBAY-SOA-REQUEST-DATA-FORMAT: XML',
    'X-EBAY-SOA-GLOBAL-ID: EBAY-GB',
    'X-EBAY-SOA-SECURITY-APPNAME: *hidden*',
    'Content-Type: text/xml;charset=utf-8',
  );

  $session  = curl_init($endpoint);                       // create a curl session
  curl_setopt($session, CURLOPT_POST, true);              // POST request type
  curl_setopt($session, CURLOPT_HTTPHEADER, $headers);    // set headers using $headers array
  curl_setopt($session, CURLOPT_POSTFIELDS, $xmlrequest); // set the body of the POST
  curl_setopt($session, CURLOPT_RETURNTRANSFER, true);    // return values as a string, not to std out

  $responsexml = curl_exec($session);                     // send the request
  curl_close($session);                                   // close the session
  return $responsexml;                                    // returns a string

}  // End of constructPostCallAndGetResponse function
?>

XML -

<?xml version="1.0"?>
<config version="1.0">
	<city id="0">
		<name>Oxford</name>
		<region>Oxfordshire</region>
		<country>United Kingdom</country>
		<weather>http://www.google.com/ig/api?weather=Oxford+GB</weather>
		<news>http://feeds.bbci.co.uk/news/england/oxford/rss.xml</news>
		<map>
			<lat>51.45</lat>
			<long>-2.583333</long>
			<scale>3000</scale>
		</map>
	</city>
	<city id="1">
		<name>Grenoble</name>
		<region>Rhone-Alpes</region>
		<country>France</country>
		<weather>http://www.google.com/ig/api?weather=Grenoble+FR</weather>
		<news>http://www.guide2rhonealpes.com/news_rss.asp</news>
		<map>
			<lat>45.185602</lat>
			<long>5.740748</long>
			<scale>3000</scale>
		</map>
	</city>
</config>

Any help is really appreciated.

Recommended Answers

All 17 Replies

Member Avatar for diafol

So you want to read in

<city id="0">
		<name>Oxford</name>
		<region>Oxfordshire</region>

to the script and then use that in:

$query = 'oxford, oxfordshire';  // Supply your own query keywords as needed

e.g.

$query = "'$name, $region'";

Is that it? If so:

$reader = new XMLReader(); 
$reader->open('trial.xml'); 
while ($reader->read()) { 
	if($reader->nodeType == XMLREADER::ELEMENT){
			
		if ($reader->name == "name"){ 
			$reader->read(); 
			$name = trim($reader->value); 
		}elseif($reader->name == "region"){ 
		   	$reader->read(); 
		   	$region = trim($reader->value); 
		}
		if(!empty($name) && !empty($region)){
			$city_array[] = "'$name, $region'";
			$name="";$region="";
		}
	}
}


foreach($city_array as $query){
   //put your exisitng code in here (query set automatically to each name/region in your xml file
}

Hey, thanks for your answer, it's reading the name and region just as I wanted, but unfortunately it isn't displaying any results now, I'm not sure if I've put the existing code in the correct place.

Live example - richh.co.uk/dsa2/ebay-uk.php

<?php
error_reporting(E_ALL);  // Turn on all errors, warnings, and notices for easier debugging
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';  // URL to call

$reader = new XMLReader(); 
$reader->open('config.xml'); 
while ($reader->read()) { 
	if($reader->nodeType == XMLREADER::ELEMENT){
 
		if ($reader->name == "name"){ 
			$reader->read(); 
			$name = trim($reader->value); 
		}elseif($reader->name == "region"){ 
		   	$reader->read(); 
		   	$region = trim($reader->value); 
		}
		if(!empty($name) && !empty($region)){
			$city_array[] = "'$name, $region'";
			$name="";$region="";
		}
	}
}
 
 
foreach($city_array as $query){
   //put your exisitng code in here (query set automatically to each name/region in your xml file_exists
   }
   // Create a PHP array of the item filters you want to use in your request
$filterarray =
  array(
    array(
    'name' => 'MaxPrice',
    'value' => '25',
    'paramName' => 'Currency',
    'paramValue' => 'GBP'),
    array(
    'name' => 'FreeShippingOnly',
    'value' => 'true',
    'paramName' => '',
    'paramValue' => ''),
    array(
    'name' => 'ListingType',
    'value' => array('AuctionWithBIN','FixedPrice','StoreInventory'),
    'paramName' => '',
    'paramValue' => ''),
  );

// Generates an XML snippet from the array of item filters
function buildXMLFilter ($filterarray) {
  global $xmlfilter;
  // Iterate through each filter in the array
  foreach ($filterarray as $itemfilter) {
    $xmlfilter .= "<itemFilter>\n";
    // Iterate through each key in the filter
    foreach($itemfilter as $key => $value) {
      if(is_array($value)) {
        // If value is an array, iterate through each array value
        foreach($value as $arrayval) {
          $xmlfilter .= " <$key>$arrayval</$key>\n";
        }
      }
      else {
        if($value != "") {
          $xmlfilter .= " <$key>$value</$key>\n";
        }
      }
    }
    $xmlfilter .= "</itemFilter>\n";
  }
  return "$xmlfilter";
} // End of buildXMLFilter function

// Build the item filter XML code
buildXMLFilter($filterarray);

// Construct the findItemsByKeywords POST call
// Load the call and capture the response returned by the eBay API
// the constructCallAndGetResponse function is defined below
$resp = simplexml_load_string(constructPostCallAndGetResponse($endpoint, $query, $xmlfilter));

// Check to see if the call was successful, else print an error
if ($resp->ack == "Success") {
  $results = '';  // Initialize the $results variable

  // Parse the desired information from the response
  foreach($resp->searchResult->item as $item) {
    $pic   = $item->galleryURL;
    $link  = $item->viewItemURL;
    $title = $item->title;

    // Build the desired HTML code for each searchResult.item node and append it to $results
    $results .= "<tr><td><img src=\"$pic\"></td><td><a href=\"$link\">$title</a></td></tr>";
  }
}
else {  // If the response does not indicate 'Success,' print an error
  $results  = "<h3>Oops! The request was not successful. Make sure you are using a valid ";
  $results .= "AppID for the Production environment.</h3>";
}

?>

<!-- Build the HTML page with values from the call response -->
<html>
<head>
<title>eBay Search Results for <?php echo $query; ?></title>
<style type="text/css">body {font-family: arial, sans-serif;} </style>
</head>
<body>

<h1>eBay Search Results for <?php echo $query; ?></h1>

<table>
<tr>
  <td>
    <?php echo $results;?>
  </td>
</tr>
</table>

</body>
</html>

<?php
function constructPostCallAndGetResponse($endpoint, $query, $xmlfilter) {
  global $xmlrequest;

  // Create the XML request to be POSTed
  $xmlrequest  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  $xmlrequest .= "<findItemsByKeywordsRequest xmlns=\"http://www.ebay.com/marketplace/search/v1/services\">\n";
  $xmlrequest .= "<keywords>";
  $xmlrequest .= $query;
  $xmlrequest .= "</keywords>\n";
  $xmlrequest .= $xmlfilter;
  $xmlrequest .= "<paginationInput>\n <entriesPerPage>3</entriesPerPage>\n</paginationInput>\n";
  $xmlrequest .= "</findItemsByKeywordsRequest>";

  // Set up the HTTP headers
  $headers = array(
    'X-EBAY-SOA-OPERATION-NAME: findItemsByKeywords',
    'X-EBAY-SOA-SERVICE-VERSION: 1.3.0',
    'X-EBAY-SOA-REQUEST-DATA-FORMAT: XML',
    'X-EBAY-SOA-GLOBAL-ID: EBAY-GB',
    'X-EBAY-SOA-SECURITY-APPNAME: *hidden*',
    'Content-Type: text/xml;charset=utf-8',
  );

  $session  = curl_init($endpoint);                       // create a curl session
  curl_setopt($session, CURLOPT_POST, true);              // POST request type
  curl_setopt($session, CURLOPT_HTTPHEADER, $headers);    // set headers using $headers array
  curl_setopt($session, CURLOPT_POSTFIELDS, $xmlrequest); // set the body of the POST
  curl_setopt($session, CURLOPT_RETURNTRANSFER, true);    // return values as a string, not to std out

  $responsexml = curl_exec($session);                     // send the request
  curl_close($session);                                   // close the session
  return $responsexml;                                    // returns a string

}  // End of constructPostCallAndGetResponse function
?>
Member Avatar for diafol

You can take out the functions / some vars and place then before any loops - you don't want to be declaring these over and over again.

Put some echoes in your code in stategic places to keep an eye on variable values.

Or have a look at http://www.firephp.org/

Thanks a lot, got it working now! That firephp is extremely useful.

One extra thing, how would I change the $reader code that you provided so that it reads the individual city id's from the XML? I have two files with the same PHP code, but I need one to read the name and region from id 0 (Oxford, Oxfordshire), and the other to read id 1 (Grenoble, Rhone-Alpes).

$reader = new XMLReader(); 
$reader->open('trial.xml'); 
while ($reader->read()) { 
	if($reader->nodeType == XMLREADER::ELEMENT){
			
		if ($reader->name == "name"){ 
			$reader->read(); 
			$name = trim($reader->value); 
		}elseif($reader->name == "region"){ 
		   	$reader->read(); 
		   	$region = trim($reader->value); 
		}
		if(!empty($name) && !empty($region)){
			$city_array[] = "'$name, $region'";
			$name="";$region="";
		}
	}
}


foreach($city_array as $query){
   //put your exisitng code in here (query set automatically to each name/region in your xml file
}
<?xml version="1.0"?>
<config version="1.0">
	<city id="0">
		<name>Oxford</name>
		<region>Oxfordshire</region>
		<country>United Kingdom</country>
		<weather>http://www.google.com/ig/api?weather=Oxford+GB</weather>
		<news>http://feeds.bbci.co.uk/news/england/oxford/rss.xml</news>
		<map>
			<lat>51.45</lat>
			<long>-2.583333</long>
			<scale>3000</scale>
		</map>
	</city>
	<city id="1">
		<name>Grenoble</name>
		<region>Rhone-Alpes</region>
		<country>France</country>
		<weather>http://www.google.com/ig/api?weather=Grenoble+FR</weather>
		<news>http://www.guide2rhonealpes.com/news_rss.asp</news>
		<map>
			<lat>45.185602</lat>
			<long>5.740748</long>
			<scale>3000</scale>
		</map>
	</city>
</config>
Member Avatar for diafol

OK forget it, use SimpleXML:

$txt = file_get_contents('trial.xml');
$cities = new SimpleXMLElement($txt);
echo $cities->city[0]->name;

and

$txt = file_get_contents('trial.xml');
$cities = new SimpleXMLElement($txt);
echo $cities->city[1]->name;

but I'd create a function in an include file and pass a parameter:

function getCity($id){
   $txt = file_get_contents('trial.xml');
   $cities = new SimpleXMLElement($txt);
   return $cities->city[$id]->name;
}

then :

echo getCity(0);
//or
echo getCity(1);

Sorry, I didn't word my previous post correctly. It isn't just the name from each city I want to echo, I just want to take the values of the name and region element of city 1 in one PHP file, and then the values of city 2 in another PHP file, but both from the same XML file.

The code you gave me works great, but only when I have 1 city in my XML, i.e -

<?xml version="1.0"?>
<config version="1.0">
	<city id="0">
		<name>Oxford</name>
		<region>Oxfordshire</region>
		<country>United Kingdom</country>
		<weather>http://www.google.com/ig/api?weather=Oxford+GB</weather>
		<news>http://feeds.bbci.co.uk/news/england/oxford/rss.xml</news>
		<map>
			<lat>51.751944</lat>
			<long>-1.257778</long>
			<scale>3000</scale>
		</map>
	</city>
</config>
Member Avatar for diafol

I don't understand why it doesn't work for you:

$txt = file_get_contents('trial.xml');
$cities = new SimpleXMLElement($txt);

echo $cities->city[1]->name . ", " . $cities->city[1]->region;

Gives me "Grenoble, Rhone-Alpes".

So just to reiterate:

in xmlhandler.php have this:

function getCityRegion($id){
   $txt = file_get_contents('trial.xml');
   $cities = new SimpleXMLElement($txt);
   return $cities->city[$id]->name . ", " . $cities->city[1]->region;
}

THen in one of your php files do this:

include("xmlhandler.php");
echo getCityRegion(0);

Then in the other php file do:

include("xmlhandler.php");
echo getCityRegion(1);

THis is for:

<?xml version="1.0"?>
<config version="1.0">
	<city id="0">
		<name>Oxford</name>
		<region>Oxfordshire</region>
		<country>United Kingdom</country>
		<weather>http://www.google.com/ig/api?weather=Oxford+GB</weather>
		<news>http://feeds.bbci.co.uk/news/england/oxford/rss.xml</news>
		<map>
			<lat>51.45</lat>
			<long>-2.583333</long>
			<scale>3000</scale>
		</map>
	</city>
	<city id="1">
		<name>Grenoble</name>
		<region>Rhone-Alpes</region>
		<country>France</country>
		<weather>http://www.google.com/ig/api?weather=Grenoble+FR</weather>
		<news>http://www.guide2rhonealpes.com/news_rss.asp</news>
		<map>
			<lat>45.185602</lat>
			<long>5.740748</long>
			<scale>3000</scale>
		</map>
	</city>
</config>

I'm really sorry if I'm frustrating you, I'm trying to figure this out and I appreciate your input.

I've tried replacing what I have with the code from your previous post but I'm just getting the region names and nothing else. I'm unsure as to whether I need to totally scrap the XMLreader you posted first of all.

I'll post my code which works at the moment, if you could advise me where to change it that would help, otherwise I understand if you'd rather just virtually punch me in the face and let me work it out for myself.

<?php
error_reporting(E_ALL);  // Turn on all errors, warnings, and notices for easier debugging
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';  // URL to call

$reader = new XMLReader(); 
$reader->open('config.xml'); 
while ($reader->read()) { 
	if($reader->nodeType == XMLREADER::ELEMENT){
 
		if ($reader->name == "name"){ 
			$reader->read(); 
			$name = trim($reader->value); 
		}elseif($reader->name == "region"){ 
		   	$reader->read(); 
		   	$region = trim($reader->value); 
		}
		if(!empty($name) && !empty($region)){
			$city_array[] = "'$name, $region'";
			$name="";$region="";
		}
	}
}
 
 
$query = implode(', ', $city_array);
   // Create a PHP array of the item filters you want to use in your request
$filterarray =
  array(
    array(
    'name' => 'MaxPrice',
    'value' => '25',
    'paramName' => 'Currency',
    'paramValue' => 'GBP'),
    array(
    'name' => 'FreeShippingOnly',
    'value' => 'true',
    'paramName' => '',
    'paramValue' => ''),
    array(
    'name' => 'ListingType',
    'value' => array('AuctionWithBIN','FixedPrice','StoreInventory'),
    'paramName' => '',
    'paramValue' => ''),
  );

// Generates an XML snippet from the array of item filters
function buildXMLFilter ($filterarray) {
  global $xmlfilter;
  // Iterate through each filter in the array
  foreach ($filterarray as $itemfilter) {
    $xmlfilter .= "<itemFilter>\n";
    // Iterate through each key in the filter
    foreach($itemfilter as $key => $value) {
      if(is_array($value)) {
        // If value is an array, iterate through each array value
        foreach($value as $arrayval) {
          $xmlfilter .= " <$key>$arrayval</$key>\n";
        }
      }
      else {
        if($value != "") {
          $xmlfilter .= " <$key>$value</$key>\n";
        }
      }
    }
    $xmlfilter .= "</itemFilter>\n";
  }
  return "$xmlfilter";
} // End of buildXMLFilter function

// Build the item filter XML code
buildXMLFilter($filterarray);

// Construct the findItemsByKeywords POST call
// Load the call and capture the response returned by the eBay API
// the constructCallAndGetResponse function is defined below
$resp = simplexml_load_string(constructPostCallAndGetResponse($endpoint, $query, $xmlfilter));

// Check to see if the call was successful, else print an error
if ($resp->ack == "Success") {
  $results = '';  // Initialize the $results variable

  // Parse the desired information from the response
  foreach($resp->searchResult->item as $item) {
    $pic   = $item->galleryURL;
    $link  = $item->viewItemURL;
    $title = $item->title;

    // Build the desired HTML code for each searchResult.item node and append it to $results
    $results .= "<tr><td><img src=\"$pic\"></td><td><a href=\"$link\">$title</a></td></tr>";
  }
}
else {  // If the response does not indicate 'Success,' print an error
  $results  = "<h3>Oops! The request was not successful. Make sure you are using a valid ";
  $results .= "AppID for the Production environment.</h3>";
}

?>

<!-- Build the HTML page with values from the call response -->
<html>
<head>
<title>eBay Search Results for <?php echo $query; ?></title>
<style type="text/css">body {font-family: arial, sans-serif;} </style>
</head>
<body>

<h1>eBay Search Results for <?php echo $query; ?></h1>

<table>
<tr>
  <td>
    <?php echo $results;?>
  </td>
</tr>
</table>

</body>
</html>

<?php
function constructPostCallAndGetResponse($endpoint, $query, $xmlfilter) {
  global $xmlrequest;

  // Create the XML request to be POSTed
  $xmlrequest  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  $xmlrequest .= "<findItemsByKeywordsRequest xmlns=\"http://www.ebay.com/marketplace/search/v1/services\">\n";
  $xmlrequest .= "<keywords>";
  $xmlrequest .= $query;
  $xmlrequest .= "</keywords>\n";
  $xmlrequest .= $xmlfilter;
  $xmlrequest .= "<paginationInput>\n <entriesPerPage>3</entriesPerPage>\n</paginationInput>\n";
  $xmlrequest .= "</findItemsByKeywordsRequest>";

  // Set up the HTTP headers
  $headers = array(
    'X-EBAY-SOA-OPERATION-NAME: findItemsByKeywords',
    'X-EBAY-SOA-SERVICE-VERSION: 1.3.0',
    'X-EBAY-SOA-REQUEST-DATA-FORMAT: XML',
    'X-EBAY-SOA-GLOBAL-ID: EBAY-GB',
    'X-EBAY-SOA-SECURITY-APPNAME: *hidden*',
    'Content-Type: text/xml;charset=utf-8',
  );

  $session  = curl_init($endpoint);                       // create a curl session
  curl_setopt($session, CURLOPT_POST, true);              // POST request type
  curl_setopt($session, CURLOPT_HTTPHEADER, $headers);    // set headers using $headers array
  curl_setopt($session, CURLOPT_POSTFIELDS, $xmlrequest); // set the body of the POST
  curl_setopt($session, CURLOPT_RETURNTRANSFER, true);    // return values as a string, not to std out

  $responsexml = curl_exec($session);                     // send the request
  curl_close($session);                                   // close the session
  return $responsexml;                                    // returns a string

}  // End of constructPostCallAndGetResponse function
?>

XML (only displays results when just 1 city is used) -

<?xml version="1.0"?>
<config version="1.0">
	<city id="0">
		<name>Oxford</name>
		<region>Oxfordshire</region>
		<country>United Kingdom</country>
		<weather>http://www.google.com/ig/api?weather=Oxford+GB</weather>
		<news>http://feeds.bbci.co.uk/news/england/oxford/rss.xml</news>
		<map>
			<lat>51.751944</lat>
			<long>-1.257778</long>
			<scale>3000</scale>
		</map>
	</city>
</config>
Member Avatar for diafol
I'm unsure as to whether I need to totally scrap the XMLreader you posted first of all.

Yes, I think that would be better. Use SimpleXML (as I used in one of my later posts). As far as punching you in the face, I don't think that will be necessary. :)

Forgive me for not debugging or modifying your code. Anybody else?

This is my personal opinion but I've always considered XML config files for PHP to be a little.... weird. This is more of a .NET way to do a config file. Why not just use a "keyword"="value" style config? Or you could even use a config.php script to hold values and also hold other useful config info.

Member Avatar for diafol

Although it may appear strange, XML is useful for exchanging data between platforms and servers

I used a config.php script originally and all was right with the world, unfortunately after the reading the specification on this project, config.xml is required.

Thanks for your input guys, I'm going to have a go at modifying it in the morning when I'm not so tired. I'll let you know how it goes.

Hey ardav, I hope you can still see my reply to this thread.

I've used simpleXML like you suggested and I'm nearly there! It's reading the city names/regions (although using the same region for both), all I need to do now is make $query read them so it searches for them on ebay. At the moment it's searching "Array" (not sure how I did that!)

I've tried $query = getCityRegion(0); but then no results are displayed.

Here's the live example - http://richh.co.uk/test/ebay-us.php

PHP -

<?php
error_reporting(E_ALL);  // Turn on all errors, warnings, and notices for easier debugging
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';  // URL to call

include("xmlhandler.php");
echo getCityRegion(0);
 
 
$query = 
   // Create a PHP array of the item filters you want to use in your request
$filterarray =
  array(
    array(
    'name' => 'MaxPrice',
    'value' => '25',
    'paramName' => 'Currency',
    'paramValue' => 'GBP'),
    array(
    'name' => 'FreeShippingOnly',
    'value' => 'true',
    'paramName' => '',
    'paramValue' => ''),
    array(
    'name' => 'ListingType',
    'value' => array('AuctionWithBIN','FixedPrice','StoreInventory'),
    'paramName' => '',
    'paramValue' => ''),
  );

// Generates an XML snippet from the array of item filters
function buildXMLFilter ($filterarray) {
  global $xmlfilter;
  // Iterate through each filter in the array
  foreach ($filterarray as $itemfilter) {
    $xmlfilter .= "<itemFilter>\n";
    // Iterate through each key in the filter
    foreach($itemfilter as $key => $value) {
      if(is_array($value)) {
        // If value is an array, iterate through each array value
        foreach($value as $arrayval) {
          $xmlfilter .= " <$key>$arrayval</$key>\n";
        }
      }
      else {
        if($value != "") {
          $xmlfilter .= " <$key>$value</$key>\n";
        }
      }
    }
    $xmlfilter .= "</itemFilter>\n";
  }
  return "$xmlfilter";
} // End of buildXMLFilter function

// Build the item filter XML code
buildXMLFilter($filterarray);

// Construct the findItemsByKeywords POST call
// Load the call and capture the response returned by the eBay API
// the constructCallAndGetResponse function is defined below
$resp = simplexml_load_string(constructPostCallAndGetResponse($endpoint, $query, $xmlfilter));

// Check to see if the call was successful, else print an error
if ($resp->ack == "Success") {
  $results = '';  // Initialize the $results variable

  // Parse the desired information from the response
  foreach($resp->searchResult->item as $item) {
    $pic   = $item->galleryURL;
    $link  = $item->viewItemURL;
    $title = $item->title;

    // Build the desired HTML code for each searchResult.item node and append it to $results
    $results .= "<tr><td><img src=\"$pic\"></td><td><a href=\"$link\">$title</a></td></tr>";
  }
}
else {  // If the response does not indicate 'Success,' print an error
  $results  = "<h3>Oops! The request was not successful. Make sure you are using a valid ";
  $results .= "AppID for the Production environment.</h3>";
}

?>

<!-- Build the HTML page with values from the call response -->
<html>
<head>
<title>eBay Search Results for <?php echo $query; ?></title>
<style type="text/css">body {font-family: arial, sans-serif;} </style>
</head>
<body>

<h1>eBay Search Results for <?php echo $query; ?></h1>

<table>
<tr>
  <td>
    <?php echo $results;?>
  </td>
</tr>
</table>

</body>
</html>

<?php
function constructPostCallAndGetResponse($endpoint, $query, $xmlfilter) {
  global $xmlrequest;

  // Create the XML request to be POSTed
  $xmlrequest  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
  $xmlrequest .= "<findItemsByKeywordsRequest xmlns=\"http://www.ebay.com/marketplace/search/v1/services\">\n";
  $xmlrequest .= "<keywords>";
  $xmlrequest .= $query;
  $xmlrequest .= "</keywords>\n";
  $xmlrequest .= $xmlfilter;
  $xmlrequest .= "<paginationInput>\n <entriesPerPage>3</entriesPerPage>\n</paginationInput>\n";
  $xmlrequest .= "</findItemsByKeywordsRequest>";

  // Set up the HTTP headers
  $headers = array(
    'X-EBAY-SOA-OPERATION-NAME: findItemsByKeywords',
    'X-EBAY-SOA-SERVICE-VERSION: 1.3.0',
    'X-EBAY-SOA-REQUEST-DATA-FORMAT: XML',
    'X-EBAY-SOA-GLOBAL-ID: EBAY-GB',
    'X-EBAY-SOA-SECURITY-APPNAME: *hidden*',
    'Content-Type: text/xml;charset=utf-8',
  );

  $session  = curl_init($endpoint);                       // create a curl session
  curl_setopt($session, CURLOPT_POST, true);              // POST request type
  curl_setopt($session, CURLOPT_HTTPHEADER, $headers);    // set headers using $headers array
  curl_setopt($session, CURLOPT_POSTFIELDS, $xmlrequest); // set the body of the POST
  curl_setopt($session, CURLOPT_RETURNTRANSFER, true);    // return values as a string, not to std out

  $responsexml = curl_exec($session);                     // send the request
  curl_close($session);                                   // close the session
  return $responsexml;                                    // returns a string

}  // End of constructPostCallAndGetResponse function
?>
Member Avatar for diafol
include("xmlhandler.php");
echo getCityRegion(0);

??

You say it doesn't work - but what's in it?

in xmlhandler we have -

<?php

function getCityRegion($id){
   $txt = file_get_contents('config.xml');
   $cities = new SimpleXMLElement($txt);
   return $cities->city[$id]->name . ", " . $cities->city[1]->region;
}

?>

Ardav I apologise, it is working perfectly. The only reason I wasn't getting any results it's because there isn't anything listed on ebay with the keywords 'grenoble, rhone-alps' so I think I will just go with the city for that one, and city/region on the other.

Thankyou very much for your help, would you mind providing me with your full name as well as any other details that I can put in my code to give you some credit?

Member Avatar for diafol

Ardav I apologise, it is working perfectly. The only reason I wasn't getting any results it's because there isn't anything listed on ebay with the keywords 'grenoble, rhone-alps' so I think I will just go with the city for that one, and city/region on the other.

Thankyou very much for your help, would you mind providing me with your full name as well as any other details that I can put in my code to give you some credit?

Don't worry about an attribution, or I'll have to remember all the websites I got my ideas from! :) Thanks anyway, but if you really feel the need, just 'Alan Davies' should suffice.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.