PHP:使用已编辑的行更新JS文件

I have the following AngularJS file called

productFactory.js

with a list of products and their details and I want to update 1 of the products.

"use strict"; 

var productFactory = angular.module('productFactory', []);

productFactory.factory('productFactory', function () {

var productFactory = {};

productFactory.products = [
    {
        productId: 1,
        name: "Product1",
        category: "Urban",
        desc: "Lorem Ipsum",
        image: "placeholder1.png;placeholder2.png;placeholder3.png",
        price: 30,
        qty: 6,
        variation: ""
    },
    {
        productId: 2,
        name: "Product2",
        category: "Street Wear",
        desc: "Lorem Ipsum",
        image: "placeholder1.png;placeholder2.png;placeholder3.png",
        price: 40,
        qty: 10,
        variation: "6,7,8,9,10,11,12"
    }
];

return productFactory;
});

In PHP I can run this script to write to the file

<?php
$script="SOME_CONTENT";
$fileName="productFactory.js";
file_put_contents($fileName, $script);
?>

How do I update just one of the products by it's 'productId'?

Best way would be to store products in some database (it could be simple JSON file which you have in productFactory.products variable.

If they were stored in JSON, you would load the file in PHP, parse it to an object with json_decode($str);, then edit what you want in that object and after that just convert it back to JSON string with (json_encode($obj);).

If you store them in a database like MySQL, the PHP processing would be simpler I think (simply call an UPDATE query for given product id).

PHP example for processing edit request:

$path = "/path/to/products.json";
$data = file_get_contents($path);
$json = json_decode($string);

foreach ($json as & $product) {
    // process only correct product
    if ($product->productId !== $_POST['productId']) {
        continue;
    }

    foreach ($_POST as $key => & $value) {
        // here should be some data validation probably
        if (isset($product[$key]) {
            $product[$key] = $value;
        }
    }
}

$newData = json_encode($json);
file_put_contents($path, $newData);