How to push a new object into array in Js using Php

Viewed 59

I have an object in Php, so I need to push it into array in Js which is located in another file called 'db.js'. Object->

$datae = array(
 'img'  => 'push-ups.webp',
 'videoname'=> $name,
 'name' => $_POST['name'],
 'text' => $_POST['description']
);

db.js inner ->

let dataGoods = [{
    "img": "push-ups.webp",
    "videoname": "igorBaitenko.mp4",
    "name": "Push-ups",
    "text": "Lorem ipsum dolor, sit amet consectetur adipisicing elit."
}, {
    "img": "push-ups.webp",
    "videoname": "igorBaitenko.mp4",
    "name": "Push-ups",
    "text": "Lorem ipsum dolor, sit amet consectetur adipisicing elit."
}];

I've tried this code to append object into array ->

$inp = file_get_contents('db.js');
$tempArray = json_decode($inp);
array_push($tempArray, json_decode($datae));

$jsonData = json_encode($tempArray, JSON_UNESCAPED_UNICODE);
file_put_contents('db.js', $jsonData );

But there was some mistakes, so I need your help please.

1 Answers

You made two mistakes:

  1. The db.js contains a JavaScript snippet, but you pass it to json_decode() as if it were JSON. You have to "convert" JavaScript to JSON, or, you can save $tempArray as JSON into db.json and load it from db.js.

  2. You use array_push($tempArray, json_decode($datae)), but $datae is an array. You can push it just like: $tempArray[] = $datae.

Related