2015-05-12 67 views
0

我正在做一个GET请求来购买API,并且它在json中给出了一个响应。 然后我使用pHp来接收响应并将其转换为放入csv文件中的数组。但是我有一个错误。json到csv与php

PHP代码:

<?php 
 
$baseUrl = 'https://[email protected]/admin/'; 
 

 
$response = json_decode(file_get_contents($baseUrl.'orders.json?limit=250')); 
 
$fp = fopen('file.csv', 'w'); 
 
var_dump($response->orders[0]->line_items[0]->properties); 
 
foreach ($response->orders as $order_index => $order) { 
 
    foreach ($order->line_items as $item_index => $item) { 
 
    echo "order: {$order_index} item: {$item_index}"; 
 
    var_dump($item->properties); 
 
\t fputcsv($fp, $item); 
 
    } 
 
} 
 
fclose($fp); 
 
?>
这是给我的错误:

Warning: fputcsv() expects parameter 2 to be array, object given in C:\wamp\www\test\index.php on line 57 

,其中第57行是:fputcsv($ FP,$项目);

你能帮我一下,如何使它成为一个数组并插入到csv中?

@Squeegy,谢谢你的回答。目前为止,唯一的问题是在csv中缺少一些重要的价值。 在他们表现出极大的回声,在这里它的第一个循环的一部分:


 

 
order: 0 item: 0 
 

 
array (size=9) 
 
    0 => 
 
    object(stdClass)[6] 
 
     public 'name' => string 'Glove Size' (length=10) 
 
     public 'value' => string 'L' (length=1) 
 
    1 => 
 
    object(stdClass)[7] 
 
     public 'name' => string 'Hat Size' (length=8) 
 
     public 'value' => string 'S/M' (length=3) 
 
    2 => 
 
    object(stdClass)[8] 
 
     public 'name' => string 'Pant Size' (length=9) 
 
     public 'value' => string '32x34' (length=5) 
 
    3 => 
 
    object(stdClass)[9] 
 
     public 'name' => string 'Right or Left Handed?' (length=21) 
 
     public 'value' => string 'Right' (length=5) 
 
    4 => 
 
    object(stdClass)[10] 
 
     public 'name' => string 'Shirt Size' (length=10) 
 
     public 'value' => string 'S' (length=1) 
 
    5 => 
 
    object(stdClass)[11] 
 
     public 'name' => string 'Shoe Size' (length=9) 
 
     public 'value' => string '10.5' (length=4) 
 
    6 => 
 
    object(stdClass)[12] 
 
     public 'name' => string 'shipping_interval_frequency' (length=27) 
 
     public 'value' => string '1' (length=1) 
 
    7 => 
 
    object(stdClass)[13] 
 
     public 'name' => string 'shipping_interval_unit_type' (length=27) 
 
     public 'value' => string 'Months' (length=6) 
 
    8 => 
 
    object(stdClass)[14] 
 
     public 'name' => string 'subscription_id' (length=15) 
 
     public 'value' => string '1522' (length=4) 
 

但在我上面写的值的CSV没有包括。任何想法为什么?

+0

发现这是个什么样子,当你不喜欢'(阵列)$ item'?如果是这种情况,你需要在循环中进一步深入一层。因为你现在有一个数组,但每个键的值仍然是一个对象。除非该对象具有'__toString()'函数,否则它只会导致NULL。所以这可能是您的CSV仍然为空的原因。 – Squeegy

+0

csv不是空的,但没有回声值 –

+0

它在csv文件中,如: 手册,1046740548,455951420,1,1,1,Athletic Style自动更新(每1个月发货),1292559264, Athletic Style自动更新(每1个月发货一次),Array,1,1,0,Array –

回答

1
$array = (array) $item; 

fputcsv($fp, $array); 

这里Convert PHP object to associative array

+0

或者不是类型转换为什么不使用'json_decode'中的'true'标志而不是 – Ghost

+0

@Ghost然后嗨应该重写循环 – splash58

+0

@Ghost好点。但是,他将不得不重写循环。我的回答非常迅速和肮脏。 – Squeegy