tags:

views:

251

answers:

4

Is there any reason why I should pick JSON over XML, or vice-versa if both are available? Tips for optimizing performance when dealing with data feeds are also appreciated!

+8  A: 

When it comes to PHP the one reason I choose XML over JSON is because even in PHP 5 there is no officially supported API for traversal. You can encode, and you can decode, and that is it. There is no validation, no efficient way to traverse key/value pairs, and all-in-all, very little support for it. Don't get me wrong, you can just use a foreach looping structure, but it really is cumbersome. JSON was touted as a great data-interchange format because JavaScript has an easy time understanding the lexical structure. So when you go from PHP to JavaScript, it is great, but when you go from JavaScript to PHP, or PHP to PHP, then JSON is not the best choice for data interchange.

hal10001
I'm not sure I 100% agree with this. Unless you are talking about a huge amount of data, iterating over an associative array in PHP is not cumbersome at all. Not to mention there are tons of tools and functions available for array manipulation.
Peter Bailey
I'm speaking mostly in comparison to SimpleXML with XPath support. Even PHP DOM XML (which isn't exactly that easy to use), still offers a bit more flexibility than a custom approach for JSON traversal. For validation you at least get DTD as well, but I can't remember the last time I used that.
hal10001
+3  A: 

I would go with JSON myself, simply because XML is very bloaty and excessively difficult to parse. JSON is small and neat, and thus saves on bandwidth, and should also speed up response times simply because it's easier to generate, faster to transmit, and quicker to decode.

JamShady
+1  A: 

No matter which method you pick, when you choose to serialize data for IO, the serialization mechanism should be transparent and replaceable. If you find that JSON isn't working for you, you should just be able to swap out the serializer you use on the front and back, and your data structs stay the same.

That said, most of the data arrays I transmit are simply big key-value trees. I have found it easier to read my data structures raw when they aren't wrapped in XML serialization.

Zak
+1  A: 

Regarding the performance of file_get_contents() versus cURL, I believe that cURL will be slightly faster. For your application you could run some quick benchmarks to compare the two approaches.

More importantly, I would prefer cURL because file_get_contents() will not work in PHP environments which have a higher level of security implemented (e.g., *allow_url_fopen* setting is usually disabled). If your application will only ever be run on your own environment (which you control), file_get_contents() would be fine, but otherwise I'd go with cURL for portability.

BrianC