Skip to content Skip to sidebar Skip to footer

Is It Possible To Update Js File Using Php Command?

I have script.js file. and it has following array script.js 'COntent': function() { var contentFacts = { blocks: { 'block1': {

Solution 1:

JavaScript is a very poor substitute for a database or any other structured data format. In this case even more because you are trying to inject content into source code.

What you probably want is some form of structured data outside of your code for example a JSON file or an SQLite database.

PHP does support parsing from and serializing to JSON:


Possible solution

Put the contentFacts into a seperate JSON file

{
  "blocks": {
    "block1": {
      name: 'yleow',
      title: 'H2',
      type: 'content'
    }
  }
}

Manipulate JSON with PHP

$json = file($path.'/blocks.json');

$blocks = json_decode($json, true);

$blocks['block2'] = array(
  'name'  => 'blue',
  'title' => 'h3',
  'type'  => 'content'
);

Write back to JSON file

$adapted_json = json_encode($blocks);

file_put_contents($path.'/blocks.json');

Now you need to get this into your JavaScript part, I assume on the client. You can do this by requesting it from the server:

const contentPromise = fetch('/path/to/blocks.json');

contentPromise.then((blocks) => {
  // Do something with those blocks. (render them to the page?)
});

Post a Comment for "Is It Possible To Update Js File Using Php Command?"