views:

107

answers:

3

Hello,

I have a xml file on my server. I have the following two questions.

  1. How to send this xml file using php to the clients browser ?
  2. The client would be making an ajax get request to the php script that sends the xml as a response. On the server side i use php simplexml functions to parse xml data. But, on the client end what would be the best way to parse the xml data ?

Thank You

+2  A: 

You would use these two commands:

<?php
header('Content-type: text/xml');
readfile('/path/to/file.xml');

You didn't say anything about receiving XML on the server, so I'm not sure what you mean by parsing.

Regarding parsing XML in JavaScript... I defer to someone with more experience.

gahooa
I believe the function you're looking for is `readfile()`, rather than `passthru()`. (`fpassthru()` would also work, if you had a file handle rather than a path to the file.)
pix0r
@pix0r: thank you so much - I got them mixed up in memory.
gahooa
+1  A: 

set the content type in the HTTP response using the header() function as:

header('Content-Type: text/xml');

then you can write the xml file content.

You must call hearder() before any output is sent.

On client side you can parse the XML in JavaScript using DOM.

codaddict
+2  A: 

gahooa's code to send the XML file to the client should work just fine. In JavaScript, you can use the XML parser to read and manipulate it. However, this is not the approach I would recommend.

Instead, let the server convert your XML into JSON after using PHP's file_get_contents() to read the XML to a string. JavaScript can natively evaluate JSON.

You'll find that navigating the DOM of an XML is clumsy by comparison to working with native JSON.

Dolph
@Dolph: Just curious to know, will the conversion to JSON also result in performance improvement on client side?
codaddict
Without testing/researching, I would say yes. Because JSON is a native data type, it can parse the data without interpreting/running any JavaScript. Instead, the browser's JavaScript engine (written in C++, etc) would do the parsing. For XML, it would be a JavaScript library doing the parsing, and then you're interpreting/running lots of extra, *relatively* slow JavaScript.
Dolph