I have some sample JSON from an API provider and am struggling with how to replace the hard coded values with a variable using PHP.
I have tried json_encoding the JSON string and changing the resulting array but this approach seems very fragile.
Here is the sample JSON they provide:
$jsonString = '{
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://upload.wikimedia.org/wikipedia/mediawiki/b/bc/Wiki.png"
}
},
{
"type": "text",
"text": "Classify this image."
}
]
}
]
}';
This is what it looks like when I json_encode it and print_r it:
Array
(
[messages] => Array
(
[0] => Array
(
[role] => user
[content] => Array
(
[0] => Array
(
[type] => image_url
[image_url] => Array
(
[url] => https://upload.wikimedia.org/wikipedia/mediawiki/b/bc/Wiki.png
)
[1] => Array
(
[type] => text
[text] => Classify this image.
)
)
)
)
)
Google Gemini suggested the following:
$newImgUrl = "https://www.google.com/someimage.png";
$myarray2['messages']['content']['image_url'] = $newImgUrl;
With trial and error I got it to work with
$myarray2['messages'][0]['content'][0]['image_url']['url'] = $newImgUrl;
However, is there no more robust way to do this using a struct or other object. I have a lot of things to modify and trying to do this by hand every time seems error prone.
You're disassembling the example JSON string into an array, then assuming pieces of the resulting array are in specific positions, then changing just those pieces, then re-encoding the array. You'd be better off just building the equivalent array yourself, putting your variables in where you want them, and then encoding it:
$payload = [
'messages' => [
[
'role' => 'user',
'content' => [
[
'type' => 'image_url',
'image_url' => [
'url' => $newImgUrl,
],
],
[
'type' => 'text',
'text' => $newImgDesc,
],
],
],
],
];
$jsonString = json_encode($payload);