我编写了一个脚本,以XML格式显示按类别组织的所有WordPress帖子。代码为
// get all the categories from the database
$cats = get_categories();
header(\'Content-type: text/xml\');
echo \'<categories>\';
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= $cat->term_id;
echo \'<category>\';
?>
<cat_id><?php echo $cat_id; ?></cat_id>
<cat_name><?php echo $cat->name; ?></cat_name>
<posts>
<?php
query_posts("cat=$cat_id&post_per_page=2");
if (have_posts()) : while (have_posts()) : the_post();
?>
<post>
<name><?php the_title(); ?></name>
<url><?php echo get_post_meta($post->ID, \'apls_video_url\', true); ?></url>
</post>
<?php
endwhile;
endif;
?>
</posts>
</category>
<?php }
echo \'</categories>\';
我还需要JSON格式的输出。我试过了
json_encode 输出为
{"categories":{"cat_id":["555","15","14","554","13","23","26","25","27","33","17","30","29","18","28","20","9","22"],"cat_name":["Articles","Crank","Escapes","Grappling Videos","Guard Breaks","Half Guard","Japanese Jujutsu","Leg Locks","MMA","MMA Videos","Mount","North South Position","Self Defense","Side Control","Strikes","Theory & Discussions","Throws","Wrist Locks"],"posts":[{"post":[{"name":"Jiu Jitsu Instruction \\u2013 Time To Teach","url":[]},{"name":"How to deal with the Bystander Effect: Taming a Hostile Crowd","url":[]},{"name":.......
但我需要以下格式的输出
{"categories":[
{ "cat_id": "16",
"cat_name": "Arm Lock",
"posts": [
{"name": "title1", "url": "www.title1.com"},
{"name": "title2", "url": "www.title2.com"},
{"name": "title3", "url": "www.title3.com"}
]
}
{ "cat_id": "12",
"cat_name": "Punch face",
"posts": [
{"name": "title11", "url": "www.title11.com"},
{"name": "title12", "url": "www.title12.com"},
{"name": "title13", "url": "www.title13.com"}
]
}
}}
如何将输出固定到所需的格式?