Im Batman
Im Batman

Reputation: 1876

Assign PHP values inside JSON Array

Im working on this DUDAMOBILE API. Custom integration in PHP website. first it takes URL from customer.

$url = $_POST["url"]

and i want to assign this url in below code

$data = '
        {   
        "site_data":
            {               
                "original_site_url":"http://www.test.com/"
            }
        }
    ';

but not sure how to assign it to above code. i tried like this. but it doesn't work

$data = '
        {   
        "site_data":
            {               
                "original_site_url":'.$url.'
            }
        }
    ';

im getting this error Failed to parse JSON: Unexpected character ('h' (code 104))

Upvotes: 0

Views: 368

Answers (2)

Chris
Chris

Reputation: 7855

You need quotes around the value as well, otherwise it is no valid JSON string:

$data = '
        {   
        "site_data":
            {               
                "original_site_url":"'.$url.'"
            }
        }
    ';

The error is because the parser expects a double quote and finds an "h" of the beggining of the url (http....).

Upvotes: 1

kylehyde215
kylehyde215

Reputation: 1256

It's because of the slashes in the url. It's better to use json_encode rather than trying to format the json by hand.

$data = ['site_data' => ['original_site_url' => $url]];
$json = json_encode($data); // json_encode($data, JSON_PRETTY_PRINT) to keep formatting.

Upvotes: 4

Related Questions