将XSLT样式表应用于Amazon Product Advertising API XML输出

时间:2013-03-21 14:34:48

标签: php xml api xslt amazon

我正在尝试将我的XSLT样式表应用于Amazon API xml输出并在页面上显示电影标题

这是我的XSLT文件(amazon.xsl):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:aws="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
<xsl:output method="xml" version="1.0" omit-xml-declaration="yes" indent="yes" media-type="text/html"/>

<xsl:template match="/">
    <xml>
        <root>
            <xsl:apply-templates select="aws:ItemLookupResponse/aws:Items/aws:Item/aws:ItemAttributes/aws:Title" />
        </root>
        </xml>
</xsl:template>

<xsl:template match="aws:Title">
    <xsl:text>Movie title</xsl:text>
    <xsl:value-of select="."/>
</xsl:template>

</xsl:stylesheet>

这是Amazon API XML输出:

<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
   <OperationRequest>
       <HTTPHeaders>
          <Header Name="UserAgent" Value="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22"/>
       </HTTPHeaders>
       <RequestId>a1138e89-4335-4650-80f2-641e3c58b623</RequestId>
       <Arguments>
    <Argument Name="Operation" Value="ItemLookup"/>
    <Argument Name="Service" Value="AWSECommerceService"/>
    <Argument Name="Signature" Value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"/>
    <Argument Name="AssociateTag" Value="xxxxxxxxxxxxxx"/>
    <Argument Name="Version" Value="2011-08-01"/>
    <Argument Name="ItemId" Value="B004LWZWGK"/>
    <Argument Name="AWSAccessKeyId" Value="xxxxxxxxxxxxxxxxxxxx"/>
    <Argument Name="Timestamp" Value="2013-03-21T13:56:55.000Z"/>
    <Argument Name="ResponseGroup" Value="Small"/>
       </Arguments>
       <RequestProcessingTime>0.0189320000000000</RequestProcessingTime>
       </OperationRequest>
    <Items>
      <Item>
         <ItemAttributes>
           <Title>
            The Dark Knight Rises (Blu-ray/DVD Combo+UltraViolet Digital Copy)
           </Title>
         </ItemAttributes>
      </Item>
    </Items>
</ItemLookupResponse>

我找到并使用以下PHP代码搜索电影标题并在页面上显示。但是,它 仅以纯文本显示。我想应用XSLT样式,但我不知道如何在我的PHP代码中正确包含它。

如果正确使用XSLT,它会在实际标题的正上方显示“电影标题”。

amazon.php

include('aws_signed_request.php');

$public_key = 'XXXXXXXXXXXXXXXXXXXX';
$private_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$associate_tag = 'xxxxxxxxxxxxxxxxxxxxxxxxx';

// generate signed URL
$request = aws_signed_request('co.uk', array(
        'Operation' => 'ItemLookup',
        'ItemId' => 'B004LWZWGK',
        'ResponseGroup' => 'Small'), $public_key, $private_key, $associate_tag);

// do request (you could also use curl etc.)
$response = @file_get_contents($request);
if ($response === FALSE) {
    echo "Request failed.\n";
} else {

    // parse XML
    $xsl = new DOMDocument;
    $xsl->load('amazon.xsl');

    $proc = new XSLTProcessor();
    $proc->importStyleSheet($xsl);

    $doc = DOMDocument::loadXML($response);
    $transform = $proc->transformToXML($doc);
    $pxml = simplexml_load_string($transform);

    if ($pxml === FALSE) {
        echo "Response could not be parsed.\n";
    } else {
        if (isset($pxml->Items->Item->ItemAttributes->Title)) {
            echo $pxml->Items->Item->ItemAttributes->Title, "\n";
        }
    }

}

* aws_signed_request.php *

function aws_signed_request($region, $params, $public_key, $private_key, $associate_tag=NULL, $version='2011-08-01')
{    
    /*
    Parameters:
        $region - the Amazon(r) region (ca,com,co.uk,de,fr,co.jp)
        $params - an array of parameters, eg. array("Operation"=>"ItemLookup",
                        "ItemId"=>"B000X9FLKM", "ResponseGroup"=>"Small")
        $public_key - your "Access Key ID"
        $private_key - your "Secret Access Key"
        $version (optional)
    */

    // some paramters
    $method = 'GET';
    $host = 'webservices.amazon.'.$region;
    $uri = '/onca/xml';

    // additional parameters
    $params['Service'] = 'AWSECommerceService';
    $params['AWSAccessKeyId'] = $public_key;
    // GMT timestamp
    $params['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z');
    // API version
    $params['Version'] = $version;
    if ($associate_tag !== NULL) {
        $params['AssociateTag'] = $associate_tag;
    }

    // sort the parameters
    ksort($params);

    // create the canonicalized query
    $canonicalized_query = array();
    foreach ($params as $param=>$value)
    {
        $param = str_replace('%7E', '~', rawurlencode($param));
        $value = str_replace('%7E', '~', rawurlencode($value));
        $canonicalized_query[] = $param.'='.$value;
    }
    $canonicalized_query = implode('&', $canonicalized_query);

    // create the string to sign
    $string_to_sign = $method."\n".$host."\n".$uri."\n".$canonicalized_query;

    // calculate HMAC with SHA256 and base64-encoding
    $signature = base64_encode(hash_hmac('sha256', $string_to_sign, $private_key, TRUE));

    // encode the signature for the request
    $signature = str_replace('%7E', '~', rawurlencode($signature));

    // create request
    $request = 'http://'.$host.$uri.'?'.$canonicalized_query.'&Signature='.$signature;

    return $request;
}

我知道这是很多代码,但PHP中的所有内容都完美无缺,我确实在页面上显示了一个电影标题。我只是想将XSLT样式表应用到它。我是PHP的新手,无法弄清楚如何正确地完成它。

2 个答案:

答案 0 :(得分:1)

您已经创建了处理器并在第6行和第6行导入了样式表。 amazon.php中的7,但仍需要使用XSLTProcessor::transformToXML

来应用它
// parse XML
$doc = DOMDocument::loadXML($response);
$transform = $proc->transformToXML($doc);
$pxml = simplexml_load_string($transform);

答案 1 :(得分:1)

要从评论中回答您的问题,以下是如何从该输入生成HTML页面:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
         xmlns:aws="http://webservices.amazon.com/AWSECommerceService/2011-08-01"
         exclude-result-prefixes="aws">
    <xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/">
      <html>
        <head>
          <title></title>
        </head>
        <body>
          <xsl:apply-templates />
        </body>
      </html>
    </xsl:template>

  <xsl:template match="aws:Title">
    <h1>
      <xsl:text>Movie Title</xsl:text>
    </h1>
    <xsl:value-of select="." />    
  </xsl:template>
  <xsl:template match="text()" />
</xsl:stylesheet>

在样本输入上运行时,会产生:

<html>
  <head>
    <META http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title></title>
  </head>
  <body>
    <h1>Movie Title</h1>
          The Dark Knight Rises (Blu-ray/DVD Combo+UltraViolet Digital Copy)
        </body>
</html>

如果您只想生成一个剪辑的HTML以添加到您正在显示的较大页面,您可以使用它:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
         xmlns:aws="http://webservices.amazon.com/AWSECommerceService/2011-08-01"
         exclude-result-prefixes="aws">
  <xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="aws:Title">
    <div>
      <h1>
        <xsl:text>Movie Title</xsl:text>
      </h1>
      <xsl:value-of select="." />
    </div>
  </xsl:template>
  <xsl:template match="text()" />
</xsl:stylesheet>

产生:

<h1>Movie Title</h1>
      The Dark Knight Rises (Blu-ray/DVD Combo+UltraViolet Digital Copy)