0

I've written a script to display all WordPress posts organized by category in XML format. Code was

// 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>';

I need the output as JSON format also. I've tried with json_encode and output was

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

But I need output in the following 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"}
   ]
}
}}

How can I fix the output to my desired format?

1 Answer 1

1

Use this function form 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 you can use like

print json_format($your_json);
1
  • 1
    Not worked for me, output was null, but thanks for your reply.
    – PHPLearner
    Commented Oct 27, 2012 at 3:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.