如何在 php 中将 <string xmlns="http://tempuri.org/">

我发现在 php 中转换<string xmlns="http://tempuri.org/">为 json 有问题,我试图寻找一个例子但都失败了。


这是我的 PHP 脚本:


public function register() {

        $url = 'https://example.com/register';


        $post_data="Email=frank@email.com";


        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=utf-8'));   

        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

        $result = curl_exec($ch);

        echo $result;

    }

这是回应:

http://img1.mukewang.com/6441fa2f00017a3704100188.jpg

请任何人帮我解决这个问题。



墨色风雨
浏览 90回答 3
3回答

芜湖不芜

在 XML 文档中发送 JSON 是一个奇怪的想法,但无论如何。最简单(明智的方法)是用 SimpleXML 加载它,然后 JSON 只是根节点的文本......$xml = simplexml_load_string($result);echo (string)$xml;应该给[&nbsp; &nbsp; {&nbsp; &nbsp; "CreateDate": "123"&nbsp; &nbsp; }]

湖上湖

在 XML 中嵌入 JSON 很奇怪,但 IMO 他的解决方案在假设输入简单的情况下发挥得有点快和松散。此外,就 PHP 的 XML 库而言,DOMDocument 和系列往往更易于使用。$in = <<<_E_<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.com/">[    {        "foo": "bar"    }]</string>_E_;$doc = new DomDocument();$doc->loadxML($in);$json = $doc->getElementsByTagName('string')->item(0)->nodeValue;$decoded = json_decode($json, true);var_dump($json, $decoded);输出:string(24) "[    {        "foo": "bar"    }]"array(1) {  [0]=>  array(1) {    ["foo"]=>    string(3) "bar"  }}

慕桂英4014372

最后,我找到了一个解决方案,如下所示:public function register() {&nbsp; &nbsp; &nbsp; &nbsp; $url = 'https://example.com/register';&nbsp; &nbsp; &nbsp; &nbsp; $post_data="Email=frank@email.com";&nbsp; &nbsp; &nbsp; &nbsp; $ch = curl_init();&nbsp; &nbsp; &nbsp; &nbsp; curl_setopt($ch, CURLOPT_URL, $url);&nbsp; &nbsp; &nbsp; &nbsp; curl_setopt($ch, CURLOPT_POST, true);&nbsp; &nbsp; &nbsp; &nbsp; curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=utf-8'));&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);&nbsp; &nbsp; &nbsp; &nbsp; curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $result = curl_exec($ch);&nbsp; &nbsp; &nbsp; &nbsp; $xml = simplexml_load_string($result,'SimpleXMLElement',LIBXML_NOCDATA);&nbsp; &nbsp; &nbsp; &nbsp; header('Content-Type: application/json');&nbsp; &nbsp; &nbsp; &nbsp; $temp = json_decode($xml);&nbsp; &nbsp; &nbsp; &nbsp; $json = json_encode($temp[0]);&nbsp; &nbsp; &nbsp; &nbsp; echo $json;&nbsp; &nbsp; }它有效;
打开App,查看更多内容
随时随地看视频慕课网APP