Laravel 5 Decode Post Method URL

2019-09-07 06:56发布

问题:

data=%7B%22password%22%3A%221234%22%2C%22username%22%3A%22user1234%22%7D&

I have this type url from a POST request and decoded it looks like this...

data = {"password":"1234", "username":"user1234"}&

In my case, I'm trying to decode with Laravel but it doesnt work properly. How can I achieve this?

<?php

function login(Request $request)
{
    $requestData = $request->request->get('data');

    $data = json_decode($requestData, true);

    $username = $data['username'];
    $password = $data['password'];

    return new JsonResponse($username);
}

回答1:

Something like this should work:

$url = "data=%7B%22password%22%3A%221234%22%2C%22username%22%3A%22user1234%22%7D&";
$decode = urldecode($url);
$sub = substr($decode, strpos($decode,'{')+strlen('{'),strlen($decode));
$sub2 = substr($sub,0,strpos($sub,'}'));
$explode = explode(',', $sub2);
$data = array();
foreach($explode as $arrayData)
{
    $arrayData = explode(":",$arrayData);
    $key = substr($arrayData[0], 1, -1);
    $value = substr($arrayData[1], 1, -1);
    $data[$key] = $value;
}
print_r($data);