Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gerardw85's avatar

Need help getting a variable to work properly.

I'm performing a post to a third party API. The post is successful in the below example when the URL is hard coded.

$content = '{
  "url": "https://www.test.com",
  "type": "URL_UPDATED"
}';
ddd($content);

yields this

"""
{
  "url": "https://www.test.com",
  "type": "URL_UPDATED"
}
"""

However, I need the URL to be a variable. The URL I need to use is being captured in a form and being passed through an HTTP Request. I confirmed it's coming across correctly.

    $content = '{
  "url": "$request->id_url",
  "type": "URL_UPDATED"
}';
ddd($content);

yields this

"""
{
  "url": "$request->id_url",
  "type": "URL_UPDATED"
}
"""

So, now I know that my variable isn't being recognized - and I know it has something to do with the single quote wrapper and/or the double quote requirement around the URL.

Have researched for quite a while and tried different methods for escaping and refactoring $content but I can't figure it out.

0 likes
3 replies
chiefguru's avatar

@gerardw85 try a simple json_encode

$content = json_encode(['url' => $request->id_url, 'type' => 'URL_UPDATED']);
1 like
Snapey's avatar
Snapey
Best Answer
Level 122

use double quotes or concatenation, or sprintf

$content = "{
  \"url\": \"{$request->id_url}\",
  \"type\": \"URL_UPDATED\"
}";

//or

$content = '{
  "url": "' . $request->id_url . '",
  "type": "URL_UPDATED"
}';

//or

$content = sprintf('{
  "url": "%s",
  "type": "URL_UPDATED"
}', $request->id_url);
1 like

Please or to participate in this conversation.