如何将字符串从URL转换为PHP对象?我知道它不是有效的JSON格式,但我仍然不知道如何正确转换它。
以下代码返回NULL:
$url = 'https://cdn.shopify.com/s/javascripts/currencies.js';
$decodedCurrencies = json_decode(file_get_contents($url));
var_dump($decodedCurrencies);
答案 0 :(得分:3)
您可以使用正则表达式提取费率数组,然后对其进行解码。
这样的事情:
$url = 'https://cdn.shopify.com/s/javascripts/currencies.js';
$script = file_get_contents($url);
$matches = [];
preg_match('/.+(\{.+}).+/', $script, $matches);
$decodedCurrencies = json_decode($matches[1]);
var_dump($decodedCurrencies);
输出:
object(stdClass)#1 (179) {
["USD"]=>
float(1)
["EUR"]=>
float(1.1637)
["GBP"]=>
float(1.31291)
["CAD"]=>
float(0.778138)
["ARS"]=>
float(0.0566433)
["AUD"]=>
float(0.766026)
["BRL"]=>
float(0.303944)
["CLP"]=>
float(0.00157516)
...
}