【发布时间】:2017-03-20 19:17:36
【问题描述】:
我正在尝试使用 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 ..."
}
]
}
错误:运行此代码时,我收到以下“警告:在第 6 行的 /Users/andrew/Desktop/newtest.php 中为 foreach() 提供的参数无效”。
添加foreach((array)$obj as $article_array){...}时没有错误
在 if (is_object($obj)){...} 语句中包装整个 foreach 循环时也没有错误。
任何帮助或建议将不胜感激。提前致谢!
【问题讨论】:
-
file_get_contents()真的返回有效的 json 吗? -
您在 obj 中缺少一级“post”,如 json 中所示。所以如果你只做 $obj = json_decode($json, true)['post']; 它应该可以工作
-
在将 [post] 添加到 $obj && foreach 之后,我们现在回到原来的警告响应:Warning: Invalid argument provided for foreach() in /Users/andrew/Desktop/newtest.php 在线6