我正在尝试使用wp_insert_post将JSON插入到wordpress中。我打了一堵砖墙。我的代码和我的一些json可以在下面看到。
PHP:
<?php
$json_feed = "http://localhost/sample/ss-posts.json";
$json = file_get_contents($json_feed);
$obj = json_decode($json, true);
foreach($obj as $article_array){
$url = $article_array['url'];
$title = $article_array['title'];
$category = $article_array['category'];
$large_summary = $article_array['wp_post_content'];
$post = array(
'post_title' => $title,
'post_content' => $large_summary,
'post_status' => 'publish',
'post_type' => 'post',
'comment_status' => 'closed',
'post_template' => 'content.php'
);
wp_insert_post ($post, $wp_error);
}
?>
JSON数据:
{
"post":[
{
"title":"Choir to College to Commercial",
"wp_post_title":"Choir to College to Commercial",
"wp_post_content":"My entry into the world of music..."
},
{
"title":"How to Master Vocal Technique",
"wp_post_title":"How to Master Vocal Technique",
"wp_post_content":"Acquiring command over vocal technique is like ..."
},
{
"title":"How Do You Evaluate Singers?",
"wp_post_title":"How Do You Evaluate Singers?",
"wp_post_content":"Many lovers of singing say that they can't put to words ..."
}
]
}
错误:运行此代码时,我收到以下内容&#34;警告:在第6行&#34; /Users/andrew/Desktop/newtest.php中为foreach()
提供的参数无效。
添加foreach((array)$obj as $article_array){...}
在if (is_object($obj)){...}
语句中包装整个foreach循环时也没有错误。
任何帮助或建议将不胜感激。提前谢谢!
答案 0 :(得分:2)
由于JSON对象的结构是{ "post":[ {}, {}, ... ] }
,因此通过使用json_decode,rusult将为$obj['post'][ Array, Array, ... ]
。因此,在foreach
循环中,您必须遍历$obj['post']
数组而不是$obj
所以foreach必须是:
...
foreach($obj['post'] as $article_array){
...