节省在Word preSS post_meta时,是不允许的“系列化”的SimpleXMLElement“不允许、节省、Word、preSS

2023-09-11 11:16:25 作者:红人館

我的工作亚马逊子公司字preSS页面上。 对于我现在用的是aws_signed_request函数来得到亚马逊的价格和纽带。

I am working on an amazon affiliate wordpress page. For that I am using the aws_signed_request function to get the price and link from amazon.

下面是aws_signed_request函数返回的XML:

Here is the aws_signed_request function returning the xml:

    function  aws_signed_request($region, $params, $public_key, $private_key, $associate_tag) {
    $method = "GET";
    $host = "ecs.amazonaws.".$region;
    $uri = "/onca/xml";

    $params["Service"]          = "AWSECommerceService";
    $params["AWSAccessKeyId"]   = $public_key;
    $params["AssociateTag"]     = $associate_tag;
    $params["Timestamp"]        = gmdate("Y-m-d\TH:i:s\Z");
    $params["Version"]          = "2009-03-31";

    ksort($params);

    $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);

    $string_to_sign = $method."\n".$host."\n".$uri."\n".
                            $canonicalized_query;

    /* calculate the signature using HMAC, 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;

    /* I prefer using CURL */
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$request);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

    $xml_response = curl_exec($ch);

   if ($xml_response === False)
    {
        return False;
    }
    else
    {
        $parsed_xml = @simplexml_load_string($xml_response);
        return ($parsed_xml === False) ? False : $parsed_xml;
    }
} 

之后,我得到该职位的ASIN和生成的链接和价格

After that I get the asin from the post and generate the link and price

global $post;  
$asin = get_post_meta($post->ID, 'ASIN', true);

$public_key = 'xxxxxxxxxxx';
$private_key = 'xxxxxxxxxxx';
$associate_tag = 'xxxxxxxxxxx';

$xml = aws_signed_Request('de',
array(
  "MerchantId"=>"Amazon",
  "Operation"=>"ItemLookup",
  "ItemId"=>$asin,
  "ResponseGroup"=>"Medium, Offers"),
$public_key,$private_key,$associate_tag);

$item = $xml->Items->Item;

$link = $item->DetailPageURL;
$price_amount = $item->OfferSummary->LowestNewPrice->Amount;
if ($price_amount > 0) { 
    $price_rund = $price_amount/100;
    $price = number_format($price_rund, 2, ',', '.');
} else {
    $price= "n.v."; 
}

这所有的作品pretty的很好,当我回声$链接,$的价格。但我想保存的话preSS后的自定义字段中的值,所以我不必每次都运行该功能。

This all works pretty good when I echo the $link and $price. But I want to save the values in the custom fields of the wordpress post so I don't have to run the function every time.

update_post_meta($post->ID, 'Price', $price);
update_post_meta($post->ID, 'Link', $link);

这增加了价格为正确的值,但是当我想要添加的链接我得到这个错误信息:

This adds the price as the correct value, but when I want to add the link I get this error message:

未捕获的异常异常有消息的序列化   的SimpleXMLElement不允许在...

Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed' in...

但是,当我删除$ parsed_xml = ...的功能,这样可以节省空值。

But when I remove the $parsed_xml=... function, it saves an empty value.

推荐答案

当你遍历SimpleXML对象实际上是另一个SimpleXML的对象(几乎)一切恢复。这就是让你写 $本期特价货品> OfferSummary-> LowestNewPrice->金额:请求 - > OfferSummary $项目对象返回一个对象,再presenting的 OfferSummary XML节点,这样你就可以申请 - > LowestNewPrice 的对象,等等。请注意,这适用于属性太 - ! $ someNode ['someAttribute'] 将是一个对象,而不是字符串

(Nearly) everything returned when you are traversing a SimpleXML object is actually another SimpleXML object. This is what lets you write $item->OfferSummary->LowestNewPrice->Amount: requesting ->OfferSummary on the $item object returns an object representing the OfferSummary XML node, so you can request ->LowestNewPrice on that object, and so on. Note that this applies to attributes too - $someNode['someAttribute'] will be an object, not a string!

为了获得一个元素或属性的字符串内容,你必须以铸造了,使用语法(字符串)$变量。有时,PHP会知道你的意思是要做到这一点,并为你做它 - 例如,当使用回声 - 但在一般情况下,这是很好的做法为总是强制转换为字符串手动,这样你不会有任何的意外,如果你以后改变code。您也可以转换为整数使用(INT),或者使用浮动(浮点)

In order to get the string content of an element or attribute, you have to "cast" it, using the syntax (string)$variable. Sometimes, PHP will know you meant to do this, and do it for you - for instance when using echo - but in general, it's good practice to always cast to string manually so that you won't have any surprises if you change your code later. You can also cast to an integer using (int), or a float using (float).

你的问题的第二部分是SimpleXML的对象存储,而特别是在内存中,而不能是序列化(即变成一个字符串,它完整地描述的对象)。这意味着,如果你试图将它们保存到数据库或会话,你会得到你所看到的错误。如果你真的想保存XML的整个块,你可以使用 $ foo-> asXML()

The second part of your problem is that SimpleXML objects are stored rather specially in memory, and can't be "serialized" (i.e. turned into a string that completely describes the object). This means that if you try to save them into a database or session, you will get the error you're seeing. If you actually wanted to save a whole block of XML, you could use $foo->asXML().

因此​​,简而言之:

使用 $链接=(字符串)$本期特价货品> DetailPageURL; 来得到一个字符串,而不是一个对象 使用 update_post_meta($后> ID,ItemXML',$本期特价货品> asXML()); 如果你想存储整个项目 use $link = (string)$item->DetailPageURL; to get a string rather than an object use update_post_meta($post->ID, 'ItemXML', $item->asXML()); if you ever want to store the whole item