I’ve been writing a couple of web services lately which returns XML data. If I’m on a deadline and just have to get it up and running, I usually don’t care for small details, but a hobby project is another matter. When I have the time, I like to sit and tweak the code to get the response looking as clean as possible, giving meaningful error messages, logging errors to files etc.
Let’s say I’m writing an application that retrieves a list of notes from a web service. The URL for retrieving the XML data would most often look something like:
http://whatever.webservice.com/feeds/latest.php?since=timestamp
Which is fine, except one little aspect: it doesn’t tell me if I am getting data back as XML, JSON, CSV or in some other format. I would much rather prefer to have this specified in the URL. Examples of good, clean URLs would be any of the following:
http://whatever.webservice.com/feeds/xml/latest.php?since=timestamp http://whatever.webservice.com/feeds/latest.php?format=xml&since=timestamp http://whatever.webservice.com/feeds/latest.xml?since=timestamp
I personally think the last one is the prettiest. There are reasons why the two first might be “better” from a code and performance perspective though:
- The subdirectory method could handle outputting of the data in that format and only that format, not needing any if-checks.
- The query parameter method could handle a lot of different formats in the same file, and would simply call the correct function to retrieve the data in the correct format.
The last one was what I went for in the end. The problem with that is making Apache understand that this “XML” file is really a PHP file. I solved this easily with this simple .htaccess file, which forces every XML file within the directory you place it in to be run through PHP:
<Files *.xml> ForceType application/x-httpd-php </Files>
Sending the correct headers is also a bonus:
<?php header('Content-Type: text/xml; charset=utf-8');
Worth the effort? You tell me Image may be NSFW.
Clik here to view.