如何用PHP写入JS对象至本地文件?处理内存更新对象的难题
Hey there! Let's break down your two questions and tackle that tricky var members = issue step by step.
First off, plain JavaScript objects/arrays (like your members list) share nearly identical syntax with JSON, so the easiest approach is to convert the JS object to a JSON string, then use PHP's built-in file functions to write it to disk.
Here's a straightforward example:
- Get your JS object as a valid JSON string (either by serializing it in JS first, or cleaning up existing JS code snippets).
- Use PHP's
file_put_contents()to write it to a file:
// 假设你已经拿到整理好的JSON格式数据 $jsonData = '[ { "Class": "B", "Rating": "1776", "ID": "12537964", "Name": "Smith, John", "Expires": "2018.10.18" }, { "Class": "C", "Rating": "1500", "ID": "12210580", "Name": "Jones, Jim", "Expires": "2019.01.12" } ]'; // 写入JSON文件(方便后续JS或PHP读取) file_put_contents('members.json', $jsonData); // 如果需要写入PHP数组格式的文件(适合PHP直接引用) $phpArray = json_decode($jsonData, true); file_put_contents('members.php', '<?php return ' . var_export($phpArray, true) . '; ?>');
Absolutely! But there are two key steps to solve your var members = problem:
Step 1: Send the updated JS object to PHP
Since JS runs client-side (in the browser) and PHP runs server-side, you need to pass the updated members array from the browser to your PHP script. The simplest way is to serialize it to JSON and send it via an AJAX request:
Frontend (JS) code:
// 假设members已经通过push方法添加了新项 const updatedMembers = [...members, { "Class": "A", "Rating": "2000", "ID": "12345678", "Name": "Doe, Jane", "Expires": "2025.05.05" }]; // 发送到PHP脚本 fetch('save-updated-members.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(updatedMembers), }) .then(res => res.text()) .then(msg => console.log(msg));
Backend (PHP) code (save-updated-members.php):
<?php // 接收前端传来的JSON数据 $rawJson = file_get_contents('php://input'); // 验证JSON合法性 $membersArray = json_decode($rawJson, true); if ($membersArray === null) { echo 'Invalid JSON data received'; exit; } // 写入到本地文件 if (file_put_contents('updated-members.json', $rawJson)) { echo 'Updated members saved successfully!'; } else { echo 'Failed to save updated members'; } ?>
Step 2: If you're working with existing var members = code (like your snippet)
If you're trying to parse a string that includes var members = and <script> tags (instead of receiving fresh JSON from the frontend), you need to extract the pure array data first. Use PHP's regex or string manipulation to strip out the non-JSON parts:
// 你的原始JS代码片段 $jsScript = '<script> var members = [ { "Class": "B", "Rating": "1776", "ID": "12537964", "Name": "Smith, John", "Expires": "2018.10.18" }, { "Class": "C", "Rating": "1500", "ID": "12210580", "Name": "Jones, Jim", "Expires": "2019.01.12" }, { "..." } ] </script>'; // 用正则提取var members = 后面的数组内容 preg_match('/var members = (.*?);?\s*<\/script>/s', $jsScript, $matches); if (isset($matches[1])) { $cleanJson = $matches[1]; // 现在$cleanJson是纯数组的JSON格式,可以直接写入或转PHP数组 file_put_contents('extracted-members.json', $cleanJson); } else { echo 'Failed to extract members data from the script'; }
The regex works by matching everything between var members = and the closing </script> tag (ignoring any trailing semicolons or whitespace). Once you have that clean JSON string, you can handle it just like any other data in PHP.
内容的提问来源于stack exchange,提问作者verlager

