我需要从 PHP 打开一个 JS 文件,在该文件中找到一个 json 变量,并将其转换为 php 数组。
现在我不知道要使用哪个正则表达式。
// get the js file
$file = file_get_contents ("http://pve.proxmox.com/pve2-api-doc/apidoc.js");
// extract the json content of var pveapi
if ( preg_match ( "#pveapi = ({[^}]*})#", $file, $infoJson ) ) {
$arrJson = json_decode ( $infoJson [1], true );
}
// shows nothing so far :((
print_r($arrJson);
我发现很少有例子可以做到这一点,但没有一个对我有用。任何在正则表达式方面具有良好技能的人都可以帮助我吗?
本
编辑:添加了js文件的一部分:
var pveapi = [
{
"info" : {
"GET" : {
"parameters" : {
"additionalProperties" : 0
},
"permissions" : {
"user" : "all"
},
"returns" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {}
},
"links" : [
{
"rel" : "child",
"href" : "{name}"
}
]
},
"name" : "index",
"method" : "GET",
"description" : "Cluster index."
}
}
}
];
Ext.onReady(function() { ... }
最佳答案
在这种情况下,可以通过匹配行末尾的分号来找到结尾:
if (preg_match('/^var pveapi = (.*?);$/ms', $js, $matches)) {
$data = json_decode($matches[1]);
print_r($data);
}
关于javascript - 使用 PHP 和 REGEX 解析 JS 脚本以获取 JS 变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28719680/