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!
views:
251answers:
4When 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.
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.
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.
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.