convert query String to json in php

前端 未结 3 587
孤独总比滥情好
孤独总比滥情好 2021-01-07 02:49

I send a QueryString formatted text like bellow to a php Script via Ajax:

title=hello&custLength=200&custWidth=300  

And I want to

相关标签:
3条回答
  • 2021-01-07 03:16

    I realize this is old, but I've found the most concise and effective solution to be the following (assuming you can't just encode the $_GET global):

    parse_str('title=hello&custLength=200&custWidth=300', $parsed);
    
    echo json_encode($parsed);
    

    Should work for any PHP version >= 5.2.0 (when json_encode() was introduced).

    0 讨论(0)
  • 2021-01-07 03:22
    $check = "title=hello&custLength=200&custWidth=300";
    $keywords = preg_split("/[\s,=,&]+/", $check);
    $arr=array();
    for($i=0;$i<sizeof($keywords);$i++)
    {
    $arr[$keywords[$i]] = $keywords[++$i];
    }
    $obj =(object)$arr;
    echo json_encode($obj);
    

    Try This code You Get Your Desired Result

    0 讨论(0)
  • 2021-01-07 03:31

    The easiest way how to achiev JSON object from $_GET string is really simple:

    json_encode($_GET)
    

    this will produce the following json output:

    {"title":"hello","custLength":"200","custWidth":"300"}
    

    Or you can use some parse function as first (for example - save all variables into array) and then you can send the parsed output into json_encode() function.

    Without specifying detailed requirements, there are many solutions.

    0 讨论(0)
提交回复
热议问题