Get all items with all details in XML format - php

I am trying to get all items using the ebay API in XML format.
See the below code for the same.
require_once('config/ebay_config.php');
require_once('helpers/eBaySession.php');
session_start();
//SiteID must also be set in the Request's XML
//SiteID = 0 (US) - UK = 3, Canada = 2, Australia = 15, ....
//SiteID Indicates the eBay site to associate the call with
$siteID = 0;
//the call being made:
$verb = 'GetSellerList';
///Build the request Xml string
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
$requestXmlBody .= '<GetSellerListRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestXmlBody .= '<EndTimeFrom>2015-12-12T11:36:06.487Z</EndTimeFrom>';
$requestXmlBody .= '<EndTimeTo>2016-03-12T11:36:06.487Z</EndTimeTo>';
$requestXmlBody .= '<RequesterCredentials><eBayAuthToken>' . $userToken . '</eBayAuthToken></RequesterCredentials>';
$requestXmlBody .= '<UserID>****</UserID>';
$requestXmlBody .= '<DetailLevel>ItemReturnDescription</DetailLevel>';
$requestXmlBody .= '<Pagination><EntriesPerPage>200</EntriesPerPage><PageNumber>1</PageNumber></Pagination>';
$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
//send the request and get response
$responseXml = $session->sendHttpRequest($requestXmlBody);
if (stristr($responseXml, 'HTTP 404') || $responseXml == '')
die('<P>Error sending request');
//Xml string is parsed and creates a DOM Document object
$responseDoc = new DomDocument();
$responseDoc->loadXML($responseXml);
$errors = $responseDoc->getElementsByTagName('Errors');
if ($errors->length > 0) {
echo '<P><B>eBay returned the following error(s):</B>';
//display each error
//Get error code, ShortMesaage and LongMessage
$code = $errors->item(0)->getElementsByTagName('ErrorCode');
$shortMsg = $errors->item(0)->getElementsByTagName('ShortMessage');
$longMsg = $errors->item(0)->getElementsByTagName('LongMessage');
echo '<P>', $code->item(0)->nodeValue, ' : ', str_replace(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue));
echo '<BR/>User Session ID: ' . $_COOKIE["eBaySession"] . '';
if (count($longMsg) > 0)
echo '<BR>', str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue));
}
else { //no errors
//get the nodes needed
$sellerNode = $responseDoc->getElementsByTagName('Seller');
if ($sellerNode->length > 0) {
echo '<P><B>Seller</B>';
$userIDNode = $sellerNode->item(0)->getElementsByTagName('UserID');
$scoreNode = $sellerNode->item(0)->getElementsByTagName('FeedbackScore');
$regDateNode = $sellerNode->item(0)->getElementsByTagName('RegistrationDate');
echo '<BR>UserID: ', $userIDNode->item(0)->nodeValue;
echo '<BR>Feedback Score: ', $scoreNode->item(0)->nodeValue;
echo '<BR>Registration Date: ', $regDateNode->item(0)->nodeValue;
}
}
It just returns seller info, but give advice for the get all items with all details.
And also one more thing, I'm done with login ebay API, and also get a success message on ebay site from below URL but I want to throw on a particular PHP page with userid.
https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&RuName=<?php echo $RuName; ?>&SessID=<?php echo $sessionID; ?>

Presuming that when you say 'All Items' you mean that you want to retrieve all seller listings:
You need to change your DetailLevel node in your initial request to 'ReturnAll'. See the following API page for details. Please note, it is not technically recommended to use the ReturnAll DetailLevel, so you may want to find precisely what you need and only return that level of detail.
eBay GetSellerList
If you are looking for All Items in a category or something (ie not associated with your seller account) you need to use the finding API if I recall correctly.. I originally said advertising but that's not eBay =p

Related

eBay Product API getProductDetails - Product ID value xxxx is not valid for product ID type UPC

Attempting to get EPID for products in eBay Motors Parts & Accessories catalog by submitting UPC.
Here is the code for the call:
$appID = 'xxxxxxxxxxxxxxxxx';
$siteID = 'EBAY-MOTOR'; // siteID needed in request
$verb = 'getProductDetails'; // the call being made:
$version = '1.4.0'; // eBay API version
///Build the request XML request which is first part of multi-part POST
$xmlReq = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
$xmlReq .= '<' . $verb . 'Request xmlns="http://www.ebay.com/marketplace/marketplacecatalog/v1/services">' . "\n";
$xmlReq .= "<productDetailsRequest>\n";
$xmlReq .= "<dataset>DisplayableProductDetails</dataset>\n";
$xmlReq .= "<productIdentifier><UPC>" . $upc . "</UPC></productIdentifier>\n";
$xmlReq .= "</productDetailsRequest>\n";
$xmlReq .= "</" . $verb . "Request>";
// Create a new eBay session (defined below)
$session = new eBaySession_Product($appID, $version, $siteID, $verb);
$respXmlStr = $session->sendHttpRequest($xmlReq); // send multi-part request and get string XML response
print "respXmlStr: $respXmlStr\n";
if(stristr($respXmlStr, 'HTTP 404') || $respXmlStr == '')
die('<P>Error sending request');
$respXmlObj = new SimpleXMLElement($respXmlStr); // create SimpleXML object from string for easier parsing
Here is the response:
Outcome: Failure
ePID:
Error Id: 18
Error Domain: Marketplace
Error Severity: Error
Error Category: System
Error Message: Product ID value 841380031426 is not valid for product ID type UPC.
Error Subdomain: MarketplaceCatalog
Version: 1.3.1
Timestamp: 2017-03-29T16:13:43.672Z
The call works for products that are not in the Parts & Accessories catalog , e.g. a Harry Potter book but I can't get it to work for any of the auto parts UPC codes. I know that 841380031426 is a valid UPC so I'm stumped. Any help is much appreciated.
Thanks,
Jay
P.S. Already tried the Product-findProducts, Shopping->FindProducts and Finding->findItemsByProduct calls with no success.
UPC isn't a Harry Potter book upcitemdb.com/upc/841380031426
If 841380031426 is the ProductID use
$xmlReq .= "<productIdentifier><productid>" . $upc . "</productid></productIdentifier>\n";
docu is here:
https://developer.ebay.com/Devzone/product/CallRef/types/ProductIdentifier.html
One more error:
$siteID = 'EBAY-MOTOR';
An Harry Potter Book won't be at ebay motors

PHP eBay GetOrders API (Unable To fetch Any Data)

I am Trying to fetch ebay orders by using getOrders API, when i execute ebay PHP SDK it print:
"Sorry No entries found in the Time period requested. Change CreateTimeFrom/CreateTimeTo and Try again"
Please Help me...
Official ebay PHP SDK code :
<?php
/* © 2013 eBay Inc., All Rights Reserved */
/* Licensed under CDDL 1.0 - http://opensource.org/licenses/cddl1.php */
?>
<?php require_once('get-common/keys.php') ; //include keys file for auth token and other credentials ?>
<?php require_once('get-common/eBaySession.php') ; //include session file for curl operations ?>
<?php
//SiteID must also be set in the Request's XML
//SiteID = 0 (US) - UK = 3, Canada = 2, Australia = 15, ....
//SiteID Indicates the eBay site to associate the call with
$siteID = 0;
//the call being made:
$verb = 'GetOrders';
//Time with respect to GMT
//by default retreive orders in last 30 minutes
$CreateTimeFrom = gmdate("Y-m-d\TH:i:s",time()-(2*40*24*60*60)); //current time minus 80 Days
//echo "</br>";
$CreateTimeTo = gmdate("Y-m-d\TH:i:s");
//If you want to hard code From and To timings, Follow the below format in "GMT".
//$CreateTimeFrom = YYYY-MM-DDTHH:MM:SS; //GMT
//$CreateTimeTo = YYYY-MM-DDTHH:MM:SS; //GMT
///Build the request Xml string
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
$requestXmlBody .= '<GetOrdersRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
$requestXmlBody .= "<CreateTimeFrom>".$CreateTimeFrom."</CreateTimeFrom><CreateTimeTo>".$CreateTimeTo."</CreateTimeTo>";
$requestXmlBody .= '<OrderRole>Seller</OrderRole><OrderStatus>All</OrderStatus>';
$requestXmlBody .= "<RequesterCredentials><eBayAuthToken>$userToken</eBayAuthToken></RequesterCredentials>";
$requestXmlBody.="<WarningLevel>High</WarningLevel>";
$requestXmlBody .= '</GetOrdersRequest>';
//Create a new eBay session with all details pulled in from included keys.php
$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
//send the request and get response
$responseXml = $session->sendHttpRequest($requestXmlBody);
if (stristr($responseXml, 'HTTP 404') || $responseXml == '')
die('<P>Error sending request');
//echo "<pre>";
//var_dump($responseXml);
//die;
//Xml string is parsed and creates a DOM Document object
$responseDoc = new DomDocument();
$responseDoc->loadXML($responseXml);
//get any error nodes
$errors = $responseDoc->getElementsByTagName('Errors');
$response = simplexml_import_dom($responseDoc);
$entries = $response->PaginationResult->TotalNumberOfEntries;
//if there are error nodes
if ($errors->length > 0) {
echo '<P><B>eBay returned the following error(s):</B>';
//display each error
//Get error code, ShortMesaage and LongMessage
$code = $errors->item(0)->getElementsByTagName('ErrorCode');
$shortMsg = $errors->item(0)->getElementsByTagName('ShortMessage');
$longMsg = $errors->item(0)->getElementsByTagName('LongMessage');
//Display code and shortmessage
echo '<P>', $code->item(0)->nodeValue, ' : ', str_replace(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue));
//if there is a long message (ie ErrorLevel=1), display it
if (count($longMsg) > 0)
echo '<BR>', str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue));
}else { //If there are no errors, continue
if(isset($_GET['debug']))
{
header("Content-type: text/xml");
print_r($responseXml);
}else
{ //$responseXml is parsed in view.php
include_once 'view.php';
}
}
?>
I would recommend the ebay-sdk-php from devbay.net :
https://github.com/davidtsadler/ebay-sdk-php
https://github.com/davidtsadler/ebay-sdk-examples
As for the date, I could be wrong, but I think it requires DateTime. Something like
CreateTimeFrom = new DateTime('02-10-2016');
CreateTimeTo = new DateTime('02-11-2016');
But I think you will have an easier time with the ebay-sdk-php
edit:
Actually I've been messing around with this more lately.
The default works for me
$CreateTimeFrom = gmdate("Y-m-d\TH:i:s",time()-1800); //current time minus 30 minutes
$CreateTimeTo = gmdate("Y-m-d\TH:i:s");
or you can hardcode your range like the following:
//If you want to hard code From and To timings, Follow the below format in "GMT".
//$CreateTimeFrom = YYYY-MM-DDTHH:MM:SS; //GMT
//$CreateTimeTo = YYYY-MM-DDTHH:MM:SS; //GMT
such as the following:
$CreateTimeFrom = '2017-03-20T00:00:00Z'; //GMT
$CreateTimeTo = '2017-03-22T00:00:00Z'; //GMT
Alternatively, you can just simply not use CreatedTimeTo and CreatedTimeFrom and use NumberOfDays instead
which is basically just commenting out CreatedTimeTo and CreatedTimeFrom
//$requestXmlBody .= "<CreateTimeFrom>$CreateTimeFrom</CreateTimeFrom><CreateTimeTo>$CreateTimeTo</CreateTimeTo>";
and directly underneath it use NumberOfDays
$requestXmlBody .= "<NumberOfDays>2</NumberOfDays>";

How to get eBay item URL based on item ID

I would like to get the item URL based on the item ID. After searching, I found that I can use GetSingleItem to achieve my goal. However, I got an error:
eBay returned the following error(s):
2 : Unsupported API call.
The API call "GetSingleItem" is invalid or not supported in this release.
Here is my code (all configuration are correct because I can use GetOrders by using these configs):
$subverb = "GetSingleItem";
$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
$requestXmlBody .= '<GetSingleItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestXmlBody .= "<ItemID>111986554711</ItemID>";
$requestXmlBody .= '</GetSingleItemRequest>';
//Create a new eBay session with all details pulled in from included keys.php
$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $subverb);
//send the request and get response
$responseXml = $session->sendHttpRequest($requestXmlBody);
if (stristr($responseXml, 'HTTP 404') || $responseXml == '')
die('<P>Error sending request');
//Xml string is parsed and creates a DOM Document object
$responseDoc = new DomDocument();
$responseDoc->loadXML($responseXml);
//get any error nodes
$errors = $responseDoc->getElementsByTagName('Errors');
$response = simplexml_import_dom($responseDoc);
$entries = $response->PaginationResult->TotalNumberOfEntries;
//if there are error nodes
if ($errors->length > 0) {
echo '<P><B>eBay returned the following error(s):</B>';
//display each error
//Get error code, ShortMesaage and LongMessage
$code = $errors->item(0)->getElementsByTagName('ErrorCode');
$shortMsg = $errors->item(0)->getElementsByTagName('ShortMessage');
$longMsg = $errors->item(0)->getElementsByTagName('LongMessage');
//Display code and shortmessage
echo '<P>', $code->item(0)->nodeValue, ' : ', str_replace(">", ">", str_replace("<", "<", $shortMsg->item(0)->nodeValue));
//if there is a long message (ie ErrorLevel=1), display it
if (count($longMsg) > 0)
echo '<BR>', str_replace(">", ">", str_replace("<", "<", $longMsg->item(0)->nodeValue));
} else { //If there are no errors, continue
if (isset($_GET['debug'])) {
header("Content-type: text/xml");
print_r($responseXml);
} else {
print("\n; 111986554711: " . $response->Item->ViewItemURLForNaturalSearch);
}
}
Any suggestion? Thank you .
As you discovered, you don't need the API to construct a simple eBay view item landing page URL.
The URL format you discovered works, but it's very old and might not be supported in full or for much longer.
Here's a simple URL format that is pretty current that you can use:
http://www.ebay.com/itm/122225724269
I got an answer without using api. Here is the answer: after I got item ID, I can use "http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=".$item_id to show my product on ebay.
I found this uri by using GetOrders API.
OrderArray.Order .TransactionArray.Transaction .Variation .VariationViewItemURL
Tip: "not optimized for natural search"
If anyone has any idea about "GetSingleItem", I am willing to know why my code doesn't work.

XML Premature end of data

when running the code below I get the following errors:
Failed loading XML Premature end of data in tag Request line 2
Fatal error: Call to a member function asXml() on a non-object in /home4/viptrav3/public_html/wp-content/themes/voyage-child/transfer.php on line 61
Line 61 is $requestFile->asXml('trequest.xml');
But I don't see the premature closing of the XML. I want to save this as a XML file trequest.xml
//Build XML Request
$requestData = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
$requestData .= '<Request>';
// Create Request Header
$requestData .= '<Source>';
// Add Requestor ID data
$requestData .= '<RequestorID Client="' . $clientID . '" EMailAddress="' . $email . '" Password="' . $password . '" />';
// Add Requestor Preferences data
$requestData .= '<RequestorPreferences Language="' . $language . '" Currency="USD" Country="US" >';
$requestData .= '<RequestMode>' . $requestMode . '</RequestMode>';
$requestData .= '</RequestorPreferences>';
$requestData .= '</Source>';
// Create Request Body
$requestData .= '<RequestDetails>
<SearchTransferPriceRequest>
<TransferPickUp>
<PickUpCityCode>LON</PickUpCityCode>
<PickUpCode>A</PickUpCode>
<PickUpPointCode>LCY</PickUpPointCode>
</TransferPickUp>
<TransferDropOff>
<DropOffCityCode>EDI</DropOffCityCode>
<DropOffCode>H</DropOffCode>
</TransferDropOff>
<TransferDate>
2013-11-11</TransferDate>
<NumberOfPassengers>2</NumberOfPassengers>
<PreferredLanguage>E</PreferredLanguage>
</SearchTransferPriceRequest>
</RequestDetails>';
//Save Request & Display XML errors
libxml_use_internal_errors(true);
$sxe = simplexml_load_string($requestData);
if ($sxe === false) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
$requestFile = simplexml_load_string($requestData);
$requestFile->asXml('trequest.xml');
You have to close <Request> tag at the end.
Also it's not good to build XML by hand. Use DOMDocument class instead.

PHP - RSS builder

I have a old website that generate its own RSS everytime a new post is created. Everything worked when I was on a server with PHP 4 but now that the host change to PHP 5, I always have a "bad formed XML". I was using xml_parser_create() and xml_parse(...) and fwrite(..) to save everything.
Here is the example when saving (I read before save to append old RSS line of course).
function SaveXml()
{
if (!is_file($this->getFileName()))
{
//Création du fichier
$file_handler = fopen($this->getFileName(),"w");
fwrite($file_handler,"");
fclose($file_handler);
}//Fin du if
//Header xml version="1.0" encoding="utf-8"
$strFileData = '<?xml version="1.0" encoding="iso-8859-1" ?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>'.$this->getProjectName().'</title><link>http://www.mywebsite.com</link><description>My description</description><lastBuildDate>' . date("r"). '</lastBuildDate>';
//Data
reset($this->arrData);
foreach($this->arrData as $i => $value)
{
$strFileData .= '<item>';
$strFileData .= '<title>'. $this->GetNews($i,0) . '</title>';
$strFileData .= '<pubDate>'. $this->GetNews($i,1) . '</pubDate>';
$strFileData .= '<dc:creator>'. $this->GetNews($i,2) . '</dc:creator>';
$strFileData .= '<description><![CDATA['. $this->GetNews($i,3) . ']]> </description>';
$strFileData .= '<link><![CDATA['. $this->GetNews($i,4) . ']]></link>';
$strFileData .= '<guid>'. $this->GetNews($i,4) . '</guid>';
//$strFileData .= '<category>'. $this->GetNews($i,5) . '</category>';
$strFileData .= '<category>Mycategory</category>';
$strFileData .= '</item>';
}//Fin du for i
$strFileData .= '</channel></rss>';
if (file_exists($this->getFileName()))//Détruit le fichier
unlink($this->getFileName());
$file_handler = fopen($this->getFileName(),"w");
fwrite($file_handler,$strFileData);
fclose($file_handler);
}//Fin de SaveXml
My question is : how do you create and fill up your RSS in PHP?
At swcombine.com we use Feedcreator. Use that one and your problem will be gone. :)
Here is the PHP code to use it once installed:
function feed_simnews() {
$objRSS = new UniversalFeedCreator();
$objRSS->title = 'My News';
$objRSS->link = 'http://link.to/news.php';
$objRSS->description = 'daily news from me';
$objRSS->xsl = 'http://link.to/feeds/feedxsl.xsl';
$objRSS->language = 'en';
$objRSS->copyright = 'Copyright: Mine!';
$objRSS->webmaster = 'webmaster#somewhere.com';
$objRSS->syndicationURL = 'http://link.to/news/simnews.php';
$objRSS->ttl = 180;
$objImage = new FeedImage();
$objImage->title = 'my logo';
$objImage->url = 'http://link.to/feeds/logo.jpg';
$objImage->link = 'http://link.to';
$objImage->description = 'Feed provided by link.to. Click to visit.';
$objImage->width = 120;
$objImage->height = 60;
$objRSS->image = $objImage;
//Function retrieving an array of your news from date start to last week
$colNews = getYourNews(array('start_date' => 'Last week'));
foreach($colNews as $p) {
$objItem = new FeedItem();
$objItem->title = $p->title;
$objItem->description = $p->body;
$objItem->link = $p->link;
$objItem->date = $p->date;
$objItem->author = $p->author;
$objItem->guid = $p->guid;
$objRSS->addItem($objItem);
}
$objRSS->saveFeed('RSS2.0', 'http://link.to/feeds/news.xml', false);
};
Quite KISS. :)
I would use simpleXML to create the required structure and export the XML. Then I'd cache it to disk with file_put_contents().
I've used this LGPL-licensed feedcreator class in the past and it worked quite well for the very simple use I had for it.
Not a full answer, but you don't have to parse your own XML. It will hurt performance and reliability.
But definitely make sure it is well-formed. It shouldn't be very hard if you generate it by hand or using general-purpose tools. Or maybe your included HTML ruins it?
There are lots of things that can make XML malformed. It might be a problem with character entities (a '<', '>', or '&' in the data between the XML tags). Try running anything output from a database through htmlentities() when you concatenate the string. Do you have an example of the generated XML for us to look at so we can see where the problem is?
PHP5 now comes with the SimpleXML extension, it's a pretty quick way to build valid XML if your needs aren't complicated.
However, the problem you're suggesting doesn't seem to an issue of implementation more a problem of syntax. Perhaps you could update your question with a code example, or, a copy of the XML that is produced.

Categories