Simple XML to JSON with PHP

Hello all, it’s been a while since I have blogged anything, been extremely busy with personal events in my life. So to get back into the swing of things I am going to KISS this post.

I recently needed to convert XML to JSON in PHP. Thankfully, PHP has built in functionality to handle precisely this task.

First we need to get contents of the XML file, we need to use file_get_contents() and pass it the URL to the XML file. We remove the newlines, returns and tabs.

$fileContents = file_get_contents($url);

$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);

Next I replace double quotes with single quotes and trim leadign and trailing spaces, this helps to ensure the simple XML function can parse the XML appropriately. Then we call the simplexml_load_string() function.

$fileContents = trim(str_replace('"', "'", $fileContents));

$simpleXml = simplexml_load_string($fileContents);

The final step we need is to convert the XML to JSON, for that we will use the json_encode() function.

$json = json_encode($simpleXml);

That’s it! All together now:

<?php

class XmlToJson {

	public function Parse ($url) {

		$fileContents= file_get_contents($url);

		$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);

		$fileContents = trim(str_replace('"', "'", $fileContents));

		$simpleXml = simplexml_load_string($fileContents);

		$json = json_encode($simpleXml);

		return $json;

	}

}

?>

Now if we want to utilize our creation we can create a file which uses the class we created above, assuming we store the XmlToJson class in a file named XmlToJson.php. We can create a file for a specific XML web service, include our class and call it XmlToJson::Parse($url). Just for fun we’ll point to the XML for the NFL scorestrip.

<?php

include 'XmlToJson.php';

print XmlToJson::Parse("http://www.nfl.com/liveupdate/scorestrip/ss.xml");

?>

Now we can call our new file, say we name it getNflDataAsJson.php, it will return the converted JSON. Calling it from jQuery below:

$.getJSON('getNflDataAsJson.php', function(data) { 
	//do something
});

Thats all I’ve got, let me know if you have any questions, things you would do differently or general comments.

Thanks much!

Related Articles:

    Post Footer automatically generated by Add Post Footer Plugin for wordpress.

    About Sean Biefeld

    Hello all, my name is Sean Biefeld. I graduated from Baylor University with a BBA in Management Information Systems. I am currently working for McLane Advanced Technologies . The opinions expressed by me, however accurate they may be, are not necessarily those of my employer. I have been a developing software professionally since 2004. My primary development focus is on HTML, CSS, JavaScript and C#. I dabble in a little PHP and Ruby. This blog is a forum for me to post my experiences, ideas, rants, and thoughts as I traverse the mountain of life.
    This entry was posted in JSON, PHP, Web Service, XML. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
    • http://meze.myopenid.com/ meze

      Why do you need to replace double quotes with single quotes? Won’t it work with double quotes?

      • Anonymous

        i had to replace double quotes with single quotes because i was getting mal-formed JSON when just leaving the double quotes in the xml, may just have been the xml i was working with, or the way php encodes the json

        • http://meze.myopenid.com/ meze

          Interesting. XML specification allows to use double and single quotes. Simple xml parses the xml in your example successfully without any replacements in PHP 5.3.5 .

          I’d also add ‘static’ keyword to the Parse method declaration, so it won’t give a strict error “Non-static method XmlToJson::Parse() should not be called statically”

          • Anonymous

            Cool, i’ll have to change that.

    • Ryan

      Do you have any idea on how to do the reverse? JSON -> XML?

    • Jim

      This will not work if you have multiple instances of the same tag in your XML, json_encode will end up only serializing the last instance of the tag. Sorry for bursting your bubble ;)

      • Nahuels

        true! a lot of trash in the web. Please author, resear a little bit before writing a tutorial. Thanks!

        • Just a guy

          How about you take it for what it is. Read the tutorial, try it out for yourself. Post any comments for improvement. Just don’t be an asshole @Nahuels, the web doesn’t need more know-it-alls like you.

          • Name

            ” the web doesn’t need more know-it-alls like you”
            Indeed, its already filled with dont-know-anythings like you and the aforementioned type doesnt help, either. The web will need experts and people who dont buggy / shitty code without understanding the mechanic behind it. It is non-trivial to convert something so fundamentally different like XML and JSON.

            • fuckstick mcgee

              You totally a word

    • Guest

      cool man!!! Thanks

    • Vahid Rajaei

      Amazing dude – thanx

    • Searock Ruzario

      Thanks a lot.

    • Wrivas

      But the function is not “static” to access with that way:
      XmlToJson::Parse(“http://www.nfl.com/liveupdate/scorestrip/ss.xml”);

      should be:
      XmlToJson->Parse(“http://www.nfl.com/liveupdate/scorestrip/ss.xml”);

      Or add “static” statement to function :D

    • jedjhe

      Thank you so much…i have had sleepless night when XML responses are returned as a single string variable…but this greatly helped me…thanks.

      my code to further help others :

      $fileContents = file_get_contents($url);
      $fileContents = trim(str_replace(‘”‘, “‘”, $fileContents));

      $simpleXml = simplexml_load_string($fileContents);
      $json = json_encode($simpleXml);
      $json = json_decode($json);

      // then returned $json as array object variable

      • Erick Christian Rosales Cruz

        That’s what I need!

    • Sameer Chourasia

      Nice…

    • David

      this post is pretty decent.

    • http://www.webexperttips.com/ Chelsy Brown

      Nice ! It’s very good tutorial. Thanks for sharing.

    • CoursesWeb

      Thank you for this tutorial. I use the code presented in this page to convert xml to json.

    • Jimmy

      Nice! Thanks for taking the time to put this together. I didn’t expect you to write all my code for me as others do (e.g. “crappy code”, “research before writing”) and belly ache without any value add (e.g. I’m better than you – I just can’t show it). Anyway, ignore these people and keep on keepin’ on. :)