php - 使用 XML API 在 eBay 上拉入类别

标签 php html css xml

第一次发帖潜伏好久,难倒了!

一段时间以来,我一直在尝试在我的雇主 eBay 商店上获取动态类别列表,我花了很多时间来寻找答案或预先编写的代码,但得出的结论是,如果我想完成它,我我将不得不自己做(完全没问题,但很耗时)。

通过使用 eBay Dev API 测试平台,我成功地提取了我想要的类别。我发现困难的是如何设计和组织结果。

如果我可以用 CSS 定位 XML 输出的标签,这会更容易,但由于它们不是标准的,我不能。

这是我到目前为止所写的内容,'style color:red' 只是为了测试 div 是否正常工作,所有必需的凭据都存储在 'keys.php' 文件中:

<?php
/*  © 2013 eBay Inc., All Rights Reserved */ 
/* Licensed under CDDL 1.0 -  http://opensource.org/licenses/cddl1.php */
require_once('keys.php') ?>
<?php require_once('eBaySession.php') ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>GetCatagories</TITLE>

<style type="text/css">
#child {
    color:red;
}
</style>
</HEAD>
<BODY>

<?php    
    //SiteID must also be set in the Request's XML
    //SiteID = 3  (US) - UK = 3, Canada = 2, Australia = 15, ....
    //SiteID Indicates the eBay site to associate the call with
    $siteID = 3;
    //the call being made:
    $verb = 'GetStore';
    //Level / amount of data for the call to return (default = 0)
    $detailLevel = 0;


    ///Build the request Xml string
    $requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
    $requestXmlBody .= '<GetStoreRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
    $requestXmlBody .= "<RequesterCredentials><eBayAuthToken>$userToken</eBayAuthToken></RequesterCredentials>";
    $requestXmlBody .= '</GetStoreRequest>';

    //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');

    //Xml string is parsed and creates a DOM Document object
    $responseDoc = new DomDocument();
    $responseDoc->loadXML($responseXml);


    //get any error nodes
    $errors = $responseDoc->getElementsByTagName('Errors');

    //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(">", "&gt;", str_replace("<", "&lt;", $shortMsg->item(0)->nodeValue));
        //if there is a long message (ie ErrorLevel=1), display it
        if(count($longMsg) > 0)
            echo '<BR>', str_replace(">", "&gt;", str_replace("<", "&lt;", $longMsg->item(0)->nodeValue));

    }
    else //no errors
    {
        $i = 2;
        while ($i <= 188) {
                echo '<div id="catagories">';
                echo $responseDoc->getElementsByTagName("Name")->item($i++)-     >textContent;
                echo '<BR>';
                echo '</div>';
            }
        }         
?>

</BODY>
</HTML>

上面的大部分代码都是凭证检查和错误管理,实际上是最后 12 行左右的代码完成了繁重的工作。

目前它在一个长的垂直列表中输出了我所有的类别和相应的子类别,理想情况下我想缩进子类别并给他们一个较小的字体大小,最简单的方法(在我看来)应该是将它们分开并应用 CSS,但我开始认为有更简单的方法,此时欢迎任何建议或意见,

提前感谢您的帮助

最佳答案

如果您乐于使用Composer在你的元素中我开发了一个 SDK for PHP这简化了 API 的使用。下面的示例将以正确的顺序获取商店类别,并使用嵌套 <ol> 输出一个简单的树。可以使用 CSS 设置样式的元素。

<?php
require __DIR__.'/vendor/autoload.php';

use \DTS\eBaySDK\Constants;
use \DTS\eBaySDK\Trading\Services;
use \DTS\eBaySDK\Trading\Types;
use \DTS\eBaySDK\Trading\Enums;

$service = new Services\TradingService([
    'credentials' => [
        'appId'  => $appID,
        'devId'  => $devID,
        'certId' => $certID
    ],
    'authToken'   => $userToken,
    'siteId'      => Constants\SiteIds::GB
]);

$request = new Types\GetStoreRequestType();
$request->CategoryStructureOnly = true;

$response = $service->getStore($request);

$html = '';

if (isset($response->Errors)) {
    $html .= '<p>eBay returned the following error(s):<br/>';
    foreach ($response->Errors as $error) {
        $html .= sprintf(
            "%s: %s<br/>%s<br/>",
            $error->SeverityCode === Enums\SeverityCodeType::C_ERROR ? 'Error' : 'Warning',
            htmlentities($error->ShortMessage),
            htmlentities($error->LongMessage)
        );
    }
    $html .= '</p>';
}

if ($response->Ack !== 'Failure') {
    $categories = iterator_to_array($response->Store->CustomCategories->CustomCategory);
    usort($categories, 'sortCategories');
    foreach ($categories as $category) {
        $html .= '<ol>'.buildCategory($category).'</ol>';
    }
}

function buildCategory($category)
{
    $html = '<li>';
    $html .= htmlentities($category->Name);
    $children = iterator_to_array($category->ChildCategory);
    usort($children, 'sortCategories');
    foreach ($children as $child) {
        $html .= '<ol>'.buildCategory($child).'</ol>';
    }
    $html .= '</li>';

    return $html;
}

function sortCategories($a, $b)
{
    if ($a->Order === $b->Order) {
        return 0;
    }

    return ($a->Order < $b->Order) ? -1 : 1;
}

echo <<< EOF_HTML
  <!doctype html>
  <html>
    <head>
      <meta charset="utf-8">
      <title>Example</title>
      <style>
        ol {
          list-style-type: none;
        }
      </style>
    </head>
    <body>
        $html
    </body>
  </html>
EOF_HTML;

关于php - 使用 XML API 在 eBay 上拉入类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36603635/

相关文章:

php - PDO 从多个相同的表中选择

html - 倒 Angular/圆 Angular 图像 HTML

php - 在匿名函数中调用匿名函数(Inception)

php - 使用 php 自动化 UNION Mysql 查询

html - 为什么我的页眉与 Bootstrap 代码中的页脚不对齐?

javascript - 如何监控用户点击了什么

javascript - 如何让按钮点击后凹陷?

javascript - 左侧为粘性侧边栏,右侧为可滚动内容的布局

javascript - 如何设置href?

javascript - 我们可以让 set Interval 等到它里面的函数执行完吗?