为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
墨色风雨 2023-04-21 10:51:05
我发现在 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;    }这是回应:请任何人帮我解决这个问题。
查看完整描述

3 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

在 XML 文档中发送 JSON 是一个奇怪的想法,但无论如何。最简单(明智的方法)是用 SimpleXML 加载它,然后 JSON 只是根节点的文本......


$xml = simplexml_load_string($result);

echo (string)$xml;

应该给


[

    {

    "CreateDate": "123"

    }

]


查看完整回答
反对 回复 2023-04-21
?
湖上湖

TA贡献2003条经验 获得超2个赞

在 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"

  }

}


查看完整回答
反对 回复 2023-04-21
?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

最后,我找到了一个解决方案,如下所示:


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


        $xml = simplexml_load_string($result,'SimpleXMLElement',LIBXML_NOCDATA);

        header('Content-Type: application/json');

        $temp = json_decode($xml);

        $json = json_encode($temp[0]);

        echo $json;

    }

它有效;



查看完整回答
反对 回复 2023-04-21
  • 3 回答
  • 0 关注
  • 88 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信