【发布时间】:2018-09-20 08:46:46
【问题描述】:
我正在尝试将 JSON 结果转换为 CSV 文件,但是,我一直在尝试获取非对象的属性
这里是代码
$url = file_get_contents('https://crm.zoho.com/crm/private/json/Contacts/getRecords?authtoken=myAPIkey&scope=crmapi');
$data = json_decode($url);
$r = $data->response->result->Contacts->row->no[1];
//Give our CSV file a name.
$csvFileName = 'example.csv';
//Open file pointer.
fopen($csvFileName,'a');
//Loop through the associative array.
foreach($r as $row) {
$values = array_column($row['columns'], 'value');
fputcsv($fp, $values);
}
//Finally, close the file pointer.
fclose($fp);
这是 JSON 响应的示例
{
"response": {
"result": {
"Contacts": {
"row": [
{
"no": "1",
"FL": [
{
"val": "CONTACTID",
"content": "3508588000000206016"
},
{
"val": "SMOWNERID",
"content": "3508588000000176021"
},
{
"val": "Contact Owner",
"content": "Chris Yates"
},
{
"val": "First Name",
"content": "Bob"
当然,我希望它遍历每一行并保存到 CSV
提前致谢,我已经查看了一些关于 SO 的解决方案,但似乎没有一个适合我
【问题讨论】:
-
您是否收到此行中的错误?
$r = $data->response->result->Contacts->row->no[1]; -
@TamilvananN - 是的,我知道这是导致问题的原因,我似乎无法找到正确的结构
-
->row->no[1];根据你的 json 结构是错误的 -
是的,我知道 - 我通常不会使用 $data->response->result->Contacts->row[1]->FL[2]->content;要从单个行和特定元素中获取数据,但我正在努力解决这个问题
-
“row”中除了“no”和“FL”还有其他键吗?