Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用PHP/JQuery将XML转换为JSON-响应应为JSON_Javascript_Ajax_Xml_Json_Cross Domain - Fatal编程技术网

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

Javascript 使用PHP/JQuery将XML转换为JSON-响应应为JSON,javascript,ajax,xml,json,cross-domain,Javascript,Ajax,Xml,Json,Cross Domain,总之,我必须调用第三方服务,它将以XML返回响应,因为我无法访问XML。有没有办法将XML响应转换为json,以便在项目中使用 我已经试过了,但我不想硬编码我的回答 // Given an XML string def xml = '''<root> | <node>Tim</node> | <node>Tom</node> | <node&

总之,我必须调用第三方服务,它将以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"]}]}]}'

感谢您的帮助。

维基,我也遇到过类似的问题 这是您的需求代码,请将此代码放在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; 
    } 
}
?>

希望这能解决您的问题。

谢谢纳维,这正是我所期待的。做得好。
/* 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 
    });