在 THIS 上使用 PHP 和 cURL链接,返回一个包含类似于以下信息的文件:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
window['flyerData'] = {
"id":489640,
"categories":[{
"id":527,
"flyer_category_id":1201344,
"run_category_id":null,
"skipped":null,
"name":"Pharmacy",
"left":2925.0,
"bottom":-2560.0,
"right":4388.0,
"top":0.0,
"thumbnail_image_url":null
}]
}
</script>
</body>
</html>
如您所见,结果是混合的 html/javascript。我想做的是使用 window['flyerData']
这样我就可以根据需要过滤值。
如何使用 PHP 和 cURL 来实现这一点?
最佳答案
你可以做这样的事情(未经测试):
<?php
//get the contents of the curl call
$curlOutput = "<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
window['flyerData'] = {
"id":489640,
"categories":[{
"id":527,
"flyer_category_id":1201344,
"run_category_id":null,
"skipped":null,
"name":"Pharmacy",
"left":2925.0,
"bottom":-2560.0,
"right":4388.0,
"top":0.0,
"thumbnail_image_url":null
}]
}
</script>
</body>
</html>";
//strip out everything except for the values between the first '{' and the last '}'
$json = substr($curlOutput, stripos($curlOutput, '{'), strripos($curlOutput, '}'));
//parse that string as JSON
$decodedJson = json_decode($json);
var_dump(decodedJson);
var_dump(decodedJson.categories);
?>
但请注意,这种类型的解析被认为是脆弱的,因为来自 curl
调用的字符串格式不能保证继续符合当前的 HTML/JS。这就是为什么如果您有权访问一个定义良好的 API,那么它是更好的选择。
关于javascript - 使用 PHP 和 cURL 从混合文本/html/javascript 文件中提取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32259967/