0

I am creating a widget that will be installed across different sites. The widget will parse an XML feed into JPlayer, because the widget will be installed across different sites AJAX is not an option, is there a way to parse XML with javascript without using AJAX. I am trying to stay away from PHP as well.

here is code in Simple XML, but I want to rewrite it in javascript.

$url = 'http://www.startalkradio.net/?page_id=354';
$rss = simplexml_load_file($url);

$items = $rss->channel->item;
<?php


$i = 0;
$data = array();
foreach ($items as $item) {
    $data[] = array(
        'title' => (string) $item->title,
        'mp3'   => (string) $item->enclosure['url'],

    );
    if (++$i == 3) break;
}


$jsdata = json_encode($data);
kubetz
  • 8,485
  • 1
  • 22
  • 27
Alex Borsody
  • 1,908
  • 9
  • 40
  • 74
  • are you using any javascript framework? btw, I am not sure I've understood why ajax is not an option... – JMax Dec 07 '11 at 08:11
  • I want people to be able to cut and paste widget text into their site. if it is a simple html site then php will not work. also sites like hosted blogspot and wordpress do not allow php widgets. – Alex Borsody Dec 07 '11 at 08:12
  • 2
    duplicate of http://stackoverflow.com/questions/649614/xml-parsing-in-javascript – pna Dec 07 '11 at 08:17
  • I vote to close as duplicate as pointed out by pna. Please feel free to explain more what is different or what you intend to do specificaly in this question or in another – JMax Dec 07 '11 at 08:46
  • @pna: This question may be a duplicate but the accepted answer to the linked question is flat-out wrong. – Tim Down Dec 07 '11 at 09:15
  • It is completely different as this example needs to parse XML from an RSS feed from a remote url. The example above parses a snippet of pasted XML. – Alex Borsody Dec 07 '11 at 16:53

1 Answers1

3

The following will parse and XML string into an XML document in all major browsers, including IE 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;

if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
Tim Down
  • 318,141
  • 75
  • 454
  • 536