简体   繁体   中英

How to put XML data into an array/object?

Below I have a piece of PHP code that essentially rips an XML file from another site and prints it to my index.php page. I'm doing this because of access-control-allow-origin so that I can get the data using AJAX (not allowed from other domains (is this known as a proxy?)).

<?php
    header ("Content-Type:text/xml");
    $url = 'http://pathtoxmlfilehere.com/blablabla.xml';
    $xml = file_get_contents($url);
    print $xml;
?>

So, now I have this file on the same server as mine, I just need to make an AJAX call to get it, right? So, I'm using jQuery so might as well make use of $.get().

$.get('PathToLocalXmlThatIUsedPhpToDownload', function(data) {
    // What goes in here?
    // Do I need to parse the data as XML?
});

I need to put the data into an object/array (not sure which is more appropriate) so that I can manipulate/display it easily. I'm struggling to do this, if anyone can help me out I'd really appreciate it. I have read other similar questions and their solutions don't seem to work for me, hence why I've decided to post my exact situation in order to find more exact answers .

Thanks

You can specify an xml datatype in your get request. The data object will then be the XML root element:

$.get('PathToLocalXmlThatIUsedPhpToDownload', function(data) {
   //work with xml here
}, 'xml');

It's probably more efficient to work with the XML directly, rather than converting it to a javascript object and then working with the data. However, if it makes more sense in the context of your problem to use a javascript object, see the answer to this post: Tool (javascript) to convert a XML string to JSON

http://api.jquery.com/jQuery.get/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM