在 PHP 中获取 URL 响应的最佳方法是什么


what is the best method to get the response of a url in php

假设我想得到这个网址的响应:

http://www.google.com/ig/calculator?hl=en&q=100USD%3D%3FEUR

即:

{lhs: "100 美元",rhs: "79.3839803 欧元",错误: ",ICC: true}

然后检索 rhs 值。

如何在 PHP 中轻松实现这一点?

echo file_get_contents('http://www.google.com/ig/calculator?hl=en&q=100USD%3D%3FEUR');
// {lhs: "100 U.S. dollars",rhs: "79.3839803 Euros",error: "",icc: true}

它没有返回有效的 JSON,因此简单的方法是修复字符串(使其成为合法的 JSON)并对其进行解码。

像这样:

<?php
    $output = file_get_contents('http://www.google.com/ig/calculator?hl=en&q=100USD%3D%3FEUR');
    $output = str_replace('rhs','"rhs"',$output);
    $output = str_replace('lhs','"lhs"',$output);
    $output = str_replace('error','"error"',$output);
    $output = str_replace('icc','"icc"',$output);
    $json = json_decode($output);
    $rhs = $json->rhs;
?>
<?php
    $resp=file_get_contents('http://www.google.com/ig/calculator?hl=en&q=100USD%3D%3FEUR');
    $pos=strpos($resp,'rhs:')+6;
    $pos2=strpos($resp,'"',$pos);
    $euros=substr($resp,$pos,$pos2-$pos);
?>