tags:

views:

55

answers:

2

Hi All,

I have a simple XML file created in R that consists of the following lines:

<statistics>
    <mean>15.75</mean>
    <sd>2.83</sd>
</statistics>

I want to extract the mean and sd to a HTML page, that has a Flash graph and I would like this underneath:

 Statistics
 Mean = 15.75
 Standard Deviation = 2.83

What is the easiest way to achieve this?

Regards,

Anthony.

+1  A: 

You should use PHP and SimpleXml. Just load your xml with simplexml:

$xml = new SimpleXMLElement(file_get_contents("statistics.xml"));

and afterwards echo the desired elements to the page (or add them to your template engine):

echo "Mean: ".$xml->statistics[0]->mean."<br />";
echo "Standard Deviation: ".$xml->statistics[0]->sd."<br />";

If you have more then one statistics element, for example:

<statistics>
    <mean>15.75</mean>
    <sd>2.83</sd>
</statistics>
<statistics>
    <mean>25.75</mean>
    <sd>28.3</sd>
</statistics>

Simply use a foreach loop to iterate trough each element:

foreach ($xml->statistiscs as $statistic) {
    echo "Mean: ".$statistics->mean."<br />";
    echo "Standard Deviation: ".$statistics->sd."<br />";
}
Robin
Thank you so much for this. It worked with one minor change in the echo statements: echo "Mean: ".$xml->mean."<br />";
Anthony Keane
A: 

jQuery is one way to do it. This will dynamically load the xml file on the client. The downside is that you have to include the library which you can download here: www.jquery.com. It can be used to so many other things so look into it. Your code would be something like:

$(document).ready(function () {
    $.get('address/to/xml.file', function(data) {
       var mean = $(data).find('mean').text();
       var sd = $(data).find('sd').text();

       $("somecontainer").text(mean + "|" + sd);
    });
});

Or do you want some server-side language to do your xml parsing and printing?

lasseespeholt