简体   繁体   English

如何使用 PHP json_decode 解析代码

[英]How can parsing code with PHP json_decode

I need to parse this string and display the result.我需要解析这个字符串并显示结果。

Sample :样品

 "<string xmlns=\"http:\/\/schemas.microsoft.com\/2003\/10\/Serialization\/\">
{\"response\":\"0\",\"errorMsg\":\"\",\"lstsmi\":[{\"code_bordereau\":\"111111111\",\"etat\":\"yes\"},{\"code_bordereau\":\"222222222\",\"etat\":\"yes\"}]}<\/string>"

Code :代码

$response = json_decode($get_data, true);

echo $response["lstsmi"];

Your response string is in XML format and it has additional \\ marks firstly you should remove the \\ mark and use the PHP simplexml_load_string method to read XML.您的响应字符串是 XML 格式,它有额外的\\标记,首先您应该删除\\标记并使用 PHP simplexml_load_string方法读取 XML。 so try the below code所以试试下面的代码

<?php
$str="<string xmlns=\"http:\/\/schemas.microsoft.com\/2003\/10\/Serialization\/\">
{\"response\":\"0\",\"errorMsg\":\"\",\"lstsmi\":[{\"code_bordereau\":\"111111111\",\"etat\":\"yes\"},{\"code_bordereau\":\"222222222\",\"etat\":\"yes\"}]}<\/string>";
$str=str_replace("\\","",$str);
$xml = simplexml_load_string($str);

//as a xml
echo "<pre>";
print_r($xml);
echo "<pre>";

//as a json
echo $xml[0];
echo "<br/>";

//as an array
$response = json_decode($xml[0]);
echo "<pre>";
print_r($response);
echo "<pre>";

result结果

SimpleXMLElement Object
(
    [0] => 
{"response":"0","errorMsg":"","lstsmi":[{"code_bordereau":"111111111","etat":"yes"},{"code_bordereau":"222222222","etat":"yes"}]}
)
{"response":"0","errorMsg":"","lstsmi":[{"code_bordereau":"111111111","etat":"yes"},{"code_bordereau":"222222222","etat":"yes"}]}
stdClass Object
(
    [response] => 0
    [errorMsg] => 
    [lstsmi] => Array
        (
            [0] => stdClass Object
                (
                    [code_bordereau] => 111111111
                    [etat] => yes
                )

            [1] => stdClass Object
                (
                    [code_bordereau] => 222222222
                    [etat] => yes
                )

        )

)

It does not work because your code is not json format.它不起作用,因为您的代码不是 json 格式。 at first ,you have to clear your code.首先,您必须清除代码。

try this one , I hope it could be helpful for you试试这个,希望对你有帮助

<?php
$str = "<string xmlns=\"http:\/\/schemas.microsoft.com\/2003\/10\/Serialization\/\">
    {\"response\":\"0\",\"errorMsg\":\"\",\"lstsmi\":[{\"code_bordereau\":\"111111111\",\"etat\":\"yes\"},{\"code_bordereau\":\"222222222\",\"etat\":\"yes\"}]}<string>";
    
@$doc = new DOMDocument();
@$doc->loadHTML($str);
$real_json_string = $doc->textCotent;
$json = json_decode($real_json_string, true);
echo print_r($json);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM