将字符串(JS对象格式)转换为PHP对象

将字符串(JS对象格式)转换为PHP对象,php,json,Php,Json,如何将字符串从URL转换为PHP对象?我知道它不是有效的JSON格式,但我仍然不知道如何正确地转换它 以下代码返回NULL: $url = 'https://cdn.shopify.com/s/javascripts/currencies.js'; $decodedCurrencies = json_decode(file_get_contents($url)); var_dump($decodedCurrencies); 您可以使用正则表达式提取速率数组,然后对其进行解码 大概是这样的

如何将字符串从URL转换为PHP对象?我知道它不是有效的JSON格式,但我仍然不知道如何正确地转换它

以下代码返回NULL:

 $url = 'https://cdn.shopify.com/s/javascripts/currencies.js';
 $decodedCurrencies = json_decode(file_get_contents($url));
 var_dump($decodedCurrencies);

您可以使用正则表达式提取速率数组,然后对其进行解码

大概是这样的:

$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)
...
}

你必须首先提取页面内容,而不是JSON,它返回js脚本是的,我知道,但我如何将这个字符串从URL转换为PHP对象?@Zeljka你是说第2行的文件内容?@Andreas yeah..@PawełKwiatkowski,有什么问题吗?让我们一起检查并修复根本没有输出,var_dump$decodedcurrences;返回空page@PawełKwiatkowski,看起来很奇怪,我已经在php5和php7上测试了它。@PawełKwiatkowski,您能提供下一个代码的输出吗?var_dumpfile_get_contents$url;我发现了问题所在,我改变了:$matches=[];到$matches=数组;现在它正在工作:,谢谢!: