简体   繁体   English

如何将XML数据放入数组/对象?

[英]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. 下面,我有一段PHP代码,该代码实际上是从另一个站点中提取XML文件并将其打印到我的index.php页面中的。 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?)). 我这样做是因为access-control-allow-origin,所以我可以使用AJAX来获取数据(不允许从其他域(这被称为代理?)。

<?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? 所以,现在我将此文件与我的文件放在同一服务器上,我只需要进行AJAX调用就可以了,对吗? So, I'm using jQuery so might as well make use of $.get(). 因此,我使用的是jQuery,因此不妨利用$ .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. 您可以在get请求中指定xml数据类型。 The data object will then be the XML root element: data对象将成为XML根元素:

$.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. 直接使用XML,而不是将其转换为javascript对象,然后使用数据,可能会更有效。 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 但是,如果在问题的上下文中使用javascript对象更有意义,请参见此文章的答案: 工具(javascript)将XML字符串转换为JSON

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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