3

I've written a CMS which uses the PHP function json_encode to send some data back via an Ajax Request.

Unfortunately, I'm trying to load it onto a server which is running PHP version 5.1, the json_encode PHP function is not available on versions of PHP before 5.2.0.

Does anyone know of a way to encode a PH array as JSON without using the inbuilt json_encode function?

EDIT

I've used Pekka's function, but now I find JQuery won't parse the result as expected. Even though Firebug shows JSON being passed back through. My firebug window looks like this:alt text

and my jquery looks like this:

     $.ajax({
            type: "GET",
            url: "includes/function/add_users.php",
            data: str,
            dataType: 'json',
            cache: false,
            beforeSend: function(html){
                    $('#editbox').html('<img class="preloader" src="images/ajax-loader.gif"/>');
            },

            success: function(html){
                fields = html;
                $('#div1').html(fields['username']);
                $('#div2').html(fields['fname']);

But the divs : #div1 and #div2 will not load the correct data.

FOR WHY?

2
  • I assume you have closed the ajax statement correctly? closing both the success function and then the overall ajax function? Commented Mar 15, 2011 at 16:31
  • 1
    yes, they were properly closed, I just included the relevant part of the code Commented Mar 16, 2011 at 10:06

4 Answers 4

4

The User Contributed Notes to json_encode have a number of implementations. On a cursory glance, this one looks the best to me.

If you have access to PECL, I would use the extension as @Artefacto recommends.

Sign up to request clarification or add additional context in comments.

5 Comments

OK that works fine - firebug shows JSON being passed. However Jquery doesn't like it...
Ok - see the extended question above
@Ashley you will need to show some actual JSON so we can tell what's wrong with it. Alternatively, @Mark Baker's suggestion looks interesting as well.
@Ashley isn't the JSON result an Object? Meaning you need to use fields.username?
A new implementation has been proposed on User Contributed Notes, seems quite good too. Deserves a try: php.net/manual/en/function.json-encode.php#107968
1

I hit up the google... This person has made a encoder of their own:

http://www.post-hipster.com/2008/02/15/elegant-little-php-json-encoder/

Comments

1

You can use the PECL extension.

Comments

0

You can use json_encode for earlier versions of PHP 5.x if you are using an older version of PHP. It works great!

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.