javascript - 使用 PHP/JQuery 将 XML 转换为 JSON - 响应应为 JSON

标签 javascript ajax xml json cross-domain

所有,我必须调用第三方服务,它将返回 XML 格式的响应,因为我无法访问 XML。有没有办法将 XML 响应转换为 json,以便我可以在我的项目中使用

我已经尝试过这个,但我不想对我的回复进行硬编码

// Given an XML string
def xml = '''<root>
            |    <node>Tim</node>
            |    <node>Tom</node>
            |    <node>
            |      <anotherNode>another</anotherNode>
            |    </node>
            |</root>'''.stripMargin()

// Parse it
def parsed = new XmlParser().parseText( xml )

// Deal with each node:
def handle
handle = { node ->
  if( node instanceof String ) {
      node
  }
  else {
      [ (node.name()): node.collect( handle ) ]
  }
}
// Convert it to a Map containing a List of Maps
def jsonObject = [ (parsed.name()): parsed.collect { node ->
   [ (node.name()): node.collect( handle ) ]
} ]

// And dump it as Json
def json = new groovy.json.JsonBuilder( jsonObject )

// Check it's what we expected
assert json.toString() == '{"root":[{"node":["Tim"]},{"node":["Tom"]},{"node":[{"anotherNode":["another"]}]}]}'

感谢帮助。

最佳答案

Vikky,我也遇到过类似的问题 这是满足您要求的代码,将此代码放入 PHP 文件中,例如 xmltojson.php

PHP 代码:

<?php
header('content-type: application/json; charset=utf-8');
if(strlen($_GET["feed"])>2) 
{ 
    $xml = file_get_contents(urldecode($_GET["feed"])); 
    if($xml) 
    { 
        $data = @simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA); 
        $json = json_encode($data); 
        echo isset($_GET["callback"]) ? "{$_GET[�callback�]}($json)" : $json; 
    } 
}
?>

JQuery 代码:

/* Accessing the thirdparty data feed,converted xml to json using php and assigned the data to the model */
    $.getJSON("xmltojson.php",{feed:"http://www.someurl.com/registerlistxml.asp?m=313"},function(data){
        //put your code to access the json data 
    });

希望这能解决您的问题。

关于javascript - 使用 PHP/JQuery 将 XML 转换为 JSON - 响应应为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27665469/

相关文章:

javascript - js - 检查函数是否完成

javascript - 循环浏览图片

javascript - Jquery 数据表未根据下拉条目显示正确的行数

ajax - MVC3 和 JQuery 对话框打开对话框时不会提交表单

ruby - 使用 JSON 时,Nokogiri XSLT 将文档标记为 XML 类型

javascript - Bootstrap 和 D3 问题

javascript - 我如何绕过同源策略来为 Google AppEngine 站点开发 AJAX 客户端代码?

c# - 使用 C# 生成 XML 文档

c# - 无法从头开始使用命名空间创建新的 XDocument

javascript - 如何根据实时 GPS 源制作 Bing map 图钉动画