【问题标题】:convert XML to JSON using PHP/JQuery- response should be in JSON使用 PHP/JQuery 将 XML 转换为 JSON - 响应应该是 JSON
【发布时间】:2015-02-24 06:11:40
【问题描述】:

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

帮助表示赞赏。

【问题讨论】:

    标签: javascript ajax xml json cross-domain


    【解决方案1】:

    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 
        });
    

    希望这能解决您的问题。

    【讨论】:

    • 感谢 Naveen,这正是我所期待的。干得好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 2020-12-01
    • 2012-02-02
    相关资源
    最近更新 更多