1

Possible Duplicate:
PHP convert XML to JSON

Here is what my a sample of my output XML looks like:

<item>
 <Barcode>0602527522593</Barcode>
 <albumid>1818</albumid>
 <Title>Gold</Title>
 <Country>Sweden</Country>
 <Format>CD</Format>
 <Length></Length>
 <Number_of_Discs></Number_of_Discs>
 <Type>album</Type>
 <Description></Description>
 <Band_or_Artist>Adams, Ryan</Band_or_Artist>
</item>

Is there an easy to use built-in PHP function or add-in to quickly convert this to JSON and output it? If it's not built-in, which extension should I use?

Community
  • 1
  • 1
Ethan Allen
  • 14,425
  • 24
  • 101
  • 194
  • 2
    Since you say this XML is your output, it might be easier to just generate JSON from whatever your source data is, rather than generating XML and then converting it into JSON. Where is the data coming from? – Jazz May 09 '12 at 22:08

4 Answers4

1

As an alternative to do this on the client-side is the XML to JSON plugin from fyneworks.

Icarus
  • 63,293
  • 14
  • 100
  • 115
1

You can use SimpleXML (http://php.net/manual/en/book.simplexml.php) to read the XML input and then json_encode (http://php.net/manual/en/book.json.php) to create the output.

You probably just want to iterate over the node list and put everything in an array using the tag names as keys, should be fairly simple.

Polygnome
  • 7,639
  • 2
  • 37
  • 57
0

There are plenty. Here's one from IBM: http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/

LeonardChallis
  • 7,759
  • 6
  • 45
  • 76
0

Something like this?

<?php

$xmlstr = "<item>
 <Barcode>0602527522593</Barcode>
 <albumid>1818</albumid>
 <Title>Gold</Title>
 <Country>Sweden</Country>
 <Format>CD</Format>
 <Length></Length>
 <Number_of_Discs></Number_of_Discs>
 <Type>album</Type>
 <Description></Description>
 <Band_or_Artist>Adams, Ryan</Band_or_Artist>
</item>";

$movies = new SimpleXMLElement($xmlstr);
echo $output = json_encode($movies);
?>
Alan Hollis
  • 1,292
  • 3
  • 14
  • 29