如何将json的输出写入CSV?
更新:我更改了代码:如何将json的输出写入CSV?
第一个关键字正在工作,第二个不写入csv。多维数组被跳过并写为“Array”。没关系。更新的代码现在看起来像这样:
$josn_decoded = json_decode($output, true);
$file_name = "searched_book.csv";
$fp = fopen($file_name, 'w');
foreach($josn_decoded['results'] as $search_result){
fputcsv($fp, $search_result);
}
fclose($fp);
如何在CSV中以行记录更多关键字?
更新2:
这里是输出(抱歉,我不能让它显示在另一种方式):
Notice: Array to string conversion in /volume2/web/static/buzzsumo/index.php on line 78
array(25) {
["published_date"]=> int(1424081166)
["linkedin_shares"]=> int(43)
["google_plus_shares"]=> int(0)
["meta_keywords"]=> string(27) "payments technology company"
["total_shares_with_pinterest"]=> int(48)
["article_types"]=> array(1) {
[0]=> string(15) "general_article" }
["twitter_shares"]=> int(5)
["og_url"]=> string(131) "http://www.thepaypers.com//online-payments/pay-on-launches-open-payment-platform-for-white-label-payment-gateway-solutions/758641-3"
["url"]=> string(131) "http://www.thepaypers.com//online-payments/pay-on-launches-open-payment-platform-for-white-label-payment-gateway-solutions/758641-3"
["pinterest_shares"]=> int(0)
["id"]=> string(9) "405519905"
["total_shares"]=> int(48)
["title"]=> string(79) "PAY.ON launches Open Payment Platform for white label payment gateway solutions"
["thumbnail"]=> string(51) "http://www.thepaypers.com/images/linkedin-share.png"
["subdomain"]=> string(18) "www.thepaypers.com"
["num_words"]=> int(206)
["domain_name"]=> string(14) "thepaypers.com"
["total_facebook_shares"]=> int(0)
["giveaway"]=> int(0)
["infographic"]=> int(0)
["general_article"]=> int(1)
["guest_post"]=> int(0)
["interview"]=> int(0)
["video"]=> int(0)
["display_title"]=> string(254) "PAY.ON launches Open Payment Platform for white label payment gateway solutions"
}
的article_types实际上可以删除,因为在底部有相同再次。此外,我需要第一列中的关键字($ search_result)。
谢谢。
$json_str = "{'aintlist':[4,3,2,1], 'astringlist':['str1','str2']}";
$out = fopen('file.csv', 'w');
foreach(json_decode($json, true)['data'] as $key => $value) {
fputcsv($out, $value);
}
fclose($out);
fclose($fp);
欢迎来到SO!为了帮助OP,请包括解释为什么您的答案可行,以便未来的观众能够理解您的答案。 –
感谢Rohan。不幸的是我在这里得到一个错误: 未定义的变量:第65行的json 警告:提供给第65行的foreach()的无效参数。 我将发布数组,以便您看到输出。 –
@Rohan:第一个错误消失了,第二个是foreach()错误,我想我需要找出它是一个字符串还是一个int,然后正确写入它。我尝试了一切它不会工作。 –
正如你可以看到嵌套在每个结果中的一个元素是一个数组。如果您尝试将数组写入CSV,它将被转换为文本“数组”,因为CSV不支持这种情况。你必须写CSV之前对待这种情况:
foreach ($josn_decoded['results'] as $search_result)
{
$search_result['article_types'] = implode(', ', $search_result['article_types']);
fputcsv($fp, $rearch_result);
}
[转换JSON为CSV格式使用PHP]的可能的复制(http://stackoverflow.com/questions/20667418/converting-json-to-csv- format-using-php) – Wobbles
@Wobbles - 我试过,但没有奏效。 –
请记住,如果我问CSV的原因? JSON通常更容易与跨平台和语言一起工作。 – Wobbles