“:7.97, “ 货币 </跨度> “: “美元” } ] “图片”: [ { “链接”:“http://i.walmartimages.com/i/p/00/88/53/70/13/0088537013840_500X500.jpg” } ] } }, { “善良……”:[ “00885370138405” ] “库存”:[ { “频道”:“在线”, “库存:有货”, “价格”:199.99, “运费”:12.85, “ 货币 </跨度> “: “美元” } ] “图片 …
解决这个问题的步骤:
有多种方法可以在php中检索远程文件/文本。最突出的是......
运用 file_get_contents() :
file_get_contents()
$txt = file_get_contents('http://www.example.com/'); echo $txt;
和PHP的卷曲功能:
$url = 'http://www.mysite.com'; $ch = curl_init($url); // Tell curl_exec to return the text instead of sending it to STDOUT curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Don't include return header in output curl_setopt($ch, CURLOPT_HEADER, 0); $txt = curl_exec($ch); curl_close($ch); echo $txt;
curl通常是一个更好的选择,因为您可以更好地控制确切的请求参数,并在事情没有按计划进行时提供更多的错误处理可能性。
如果远程API页面返回JSON字符串,则使用json_decode()将其转换为数组,并迭代生成的数组以提取所需的值:
// retrieve the remote text using one of the above methods $txt = file_get_contents('http://www.example.com/'); // decode the json string into an array $arr = json_decode($txt); $price_arr = array(); foreach ($arr as $a) { // this is not the exact format of the data returned // from the API, just an example to demonstrate how you // would iterate over the decoded array $price_arr[] = $a['price']; }
你也可以使用PHP array_map() 函数用于更详细地解析由解码JSON字符串产生的数组,尽管简单的foreach循环对于大多数人来说已经足够了。
array_map()