XML zu Json Code Problem

Ich habe ein Skript geschrieben, um alle WordPress-Beiträge nach Kategorie im XML-Format anzuzeigen. Code war

// get all the categories from the database $cats = get_categories(); header('Content-type: text/xml'); echo ''; // loop through the categries foreach ($cats as $cat) { // setup the cateogory ID $cat_id= $cat->term_id; echo ''; ?>  name; ?>     ID, 'apls_video_url', true); ?>     <?php } echo ''; 

Ich brauche die Ausgabe auch als JSON-Format. Ich habe es mit json_encode probiert und ausgegeben

 {"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":....... 

Aber ich brauche die Ausgabe im folgenden Format

 {"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"} ] } }} 

Wie kann ich die Ausgabe an mein gewünschtes Format anpassen?

Solutions Collecting From Web of "XML zu Json Code Problem"

Verwenden Sie dieses functionsformular http://www.php.net/manual/en/function.json-encode.php#80339

 function json_format($json) { $tab = " "; $new_json = ""; $indent_level = 0; $in_string = false; $json_obj = json_decode($json); if($json_obj === false) return false; $json = json_encode($json_obj); $len = strlen($json); for($c = 0; $c < $len; $c++) { $char = $json[$c]; switch($char) { case '{': case '[': if(!$in_string) { $new_json .= $char . "\n" . str_repeat($tab, $indent_level+1); $indent_level++; } else { $new_json .= $char; } break; case '}': case ']': if(!$in_string) { $indent_level--; $new_json .= "\n" . str_repeat($tab, $indent_level) . $char; } else { $new_json .= $char; } break; case ',': if(!$in_string) { $new_json .= ",\n" . str_repeat($tab, $indent_level); } else { $new_json .= $char; } break; case ':': if(!$in_string) { $new_json .= ": "; } else { $new_json .= $char; } break; case '"': if($c > 0 && $json[$c-1] != '\\') { $in_string = !$in_string; } default: $new_json .= $char; break; } } return $new_json; } 

So können Sie wie verwenden

 print json_format($your_json);