把以下代码变成php执行<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Cookie转JSON</title> </head> <body> <div> <label for="cookie">Cookie:</label> <textarea id="cookie" name="cookie" cols="50" rows="10"></textarea> </div> <div> <button onclick="convertCookieToJson()">转换</button> </div> <div> <label for="json">JSON:</label> <textarea id="json" name="json" cols="50" rows="10"></textarea> </div> <script> function convertCookieToJson() { var cookie = document.getElementById("cookie").value; var cookiesArray = cookie.split("; "); var cookiesObject = {}; cookiesArray.forEach(function(cookie) { var parts = cookie.split("="); cookiesObject[parts[0]] = parts[1]; }); document.getElementById("json").value = JSON.stringify(cookiesObject); } </script> </body> </html>
时间: 2023-07-15 22:11:12 浏览: 68
下面是 PHP 代码:
```php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cookie转JSON</title>
</head>
<body>
<div>
<label for="cookie">Cookie:</label>
<textarea id="cookie" name="cookie" cols="50" rows="10"></textarea>
</div>
<div>
<button onclick="convertCookieToJson()">转换</button>
</div>
<div>
<label for="json">JSON:</label>
<textarea id="json" name="json" cols="50" rows="10"></textarea>
</div>
<?php
if(isset($_POST['cookie'])) {
$cookie = $_POST['cookie'];
$cookiesArray = explode("; ", $cookie);
$cookiesObject = array();
foreach($cookiesArray as $cookie) {
$parts = explode("=", $cookie);
$cookiesObject[$parts[0]] = $parts[1];
}
$json = json_encode($cookiesObject);
echo "<script>document.getElementById('json').value = '$json';</script>";
}
?>
</body>
</html>
```
修改后的代码使用了 PHP 来处理表单提交,将 cookie 转换为 JSON,并将结果自动填充到页面中的文本区域中。注意,这里使用了 PHP 的 explode() 函数来分割字符串。
阅读全文