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:


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.


include 'XmlToJson.php';

print XmlToJson::Parse("");


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!

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 Headspring . I have been a developing software professionally since 2004. My primary development focus is on HTML, CSS, JavaScript and C#. 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.
  • 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

      • 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:

    should be:

    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


  • David

    this post is pretty decent.

  • 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. :)

  • ivan molina

    hey Bro this tutorial is just working on a localhost !, how can i get this working on a server?, and also how can i create a new json file with the data parsed with this code ?

  • Chapo

    Buddy how can I save the data I got from the xml(which is now in json format)?,I don’t know,create a json file from the data converted(xml 2 json), how can I do that?

  • Druuu

    what are some examples of “doing something” with the returned data at the end with the NFL scorestrip return? Also, should any options be passed to that xml, and if so, how? Thanks. Nice tutorial.

  • Paul Swennenhuis

    Nice and smooth.
    Thanks Sean.

  • Betto

    Hello, this script work very good, but I am researching if is possible parser a web page to Json.

    For example convert to Json.

  • Philip Saa

    Very nice

  • youcef

    Thanks for the post, but it doesn’t work when you have CDATA in your xml feed. I found this works

    • Jay Teli

      The link that you provided was really helpful . thanks

  • Bouri Ayman official


  • Nice article, and if you want to check your result after converting this tool may help

  • Khaven

    Thanks for this tutorial. If you just want to convert XML To JSON use this tool:

  • atemkeng azankang

    ho man that’s a great job! thx very mush :)

  • syaj

    Joder por fin lo he logrado GRACIAS!