doujimiao7480 2014-11-10 22:23
浏览 669

使用PHP foreach循环返回key => value数组对

So I've followed a few questions on here to try and get this to work....but I just can't seem to crack it. Essentially what i'm trying to do is loop through an XML file and return key => value pairs for elements from that file. For a bit more context, I'm trying to store an item's ASIN (Amazon API) as the key and it's image URL as the value in an array.

Here's the structure of the XML file, in case these helps someone determine where my code is flawed:

<Items>
<Request>
<IsValid>True</IsValid>
<ItemSearchRequest>
<Keywords>biology</Keywords>
<ResponseGroup>Images</ResponseGroup>
<SearchIndex>Books</SearchIndex>
</ItemSearchRequest>
</Request>
<TotalResults>280951</TotalResults>
<TotalPages>28096</TotalPages>
<MoreSearchResultsUrl>
http://www.amazon.com/gp/redirect.html?camp=2025&creative=386001&location=http%3A%2F%2Fwww.amazon.com%2Fgp%2Fsearch%3Fkeywords%3Dbiology%26url%3Dsearch-alias%253Dstripbooks&linkCode=xm2&tag=comparcom035-20&SubscriptionId=AKIAIQ7UEDX4CFRSBDXA
</MoreSearchResultsUrl>
<Item>
<ASIN>0321558235</ASIN>
<SmallImage>
<URL>
http://ecx.images-amazon.com/images/I/41UWC4kbxGL._SL75_.jpg
</URL>
<Height Units="pixels">75</Height>
<Width Units="pixels">62</Width>
</SmallImage>

and here's the code I'm working with:

$xml = simplexml_load_file($SignedRequest);
$image = simplexml_load_file($getimage);



foreach ($image->Items->Item->ASIN as $key => $value) {
            $array[$key] = $image->Items->Item->SmallImage->URL;

        }

print_r($array);

My output looks like this:

Array ( [ASIN] => SimpleXMLElement Object ( [0] => http://ecx.images-amazon.com/images/I/41UWC4kbxGL._SL75_.jpg ) )

I think I'm close.....but can anyone point out what I'm doing wrong here? I can't seem to get my loop to assign the key and value properly without throwing some kind of error.

  • 写回答

2条回答 默认 最新

  • doulu4316 2014-11-10 22:44
    关注

    You are close, you just need to cast the value as a string:

    $array[$key] = (string) $image->Items->Item->SmallImage->URL;
    
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?