我在从 Web 服务获取内容/数组到我的 PHP 代码时遇到问题。当我在浏览器中输入 url 时,如 http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD ,然后浏览器中的结果显示如下:[ 1.20MYR , 0.39SGD ]。我的 PHP 代码如下所示:
$ch = curl_init('http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
echo $content;
不幸的是,我没有使用上面的代码。寻求帮助。 谢谢。
已更新
$data=array(
'amount'=>1.2,
'fromCurrency'=>'MYR',
'toCurrency'=>'SGD'
);
$data_string = json_encode($data);
$ch = curl_init('http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-type: application/json'));
$content= curl_exec($ch);
curl_close($ch);
$obj = json_decode($content);
echo $obj;
最佳答案
此页面包含由 JavaScript 加载的动态内容。例如,您可以通过访问 view-source:http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD 在 Google Chrome 中看到它。 .
如果您仔细查看页面的源代码(文件 http://server1-xeon.asuscomm.com/currency/JQuery/app_converter.js),您会发现它使用以下代码在底层获取交换数据:
$.ajax({type: "POST",
url: "WebService.asmx/YaHOO_CurrencyEx", // important: it's a relative URL!
data: "{amount:" + amount + ",fromCurrency:'" + from + "',toCurrency:'" + to + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {},
success: function (data) {
$('#results').html(' [ ' + amount + from + ' , ' + data.d.toFixed(2) + to + ' ] ');
});
因此,实际上您可以在 PHP 中发出此类请求以避免访问 http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD< 上的动态内容
页面。
更新: 我添加了更完整的解释。
当页面在 http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD 上时加载后,此页面上的 JavaScript 代码(这意味着它在客户端、浏览器中执行,而不是在您的服务器上执行)解析 URL 参数并向 URL 发出 AJAX POST
请求 http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx .它传递一个 JSON 有效负载 {amount:1.20,fromCurrency:'MYR',toCurrency:'SGD'}
并获得类似这样的响应 {"d":0.390360}
。因此,您可以直接向 http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx 发出 POST
请求。通过 curl
,在 JSON 正文中传递 amount
、fromCurrency
和 toCurrency
,然后使用 解码收到的 JSON 响应>json_decode($content);
.
关于php - PHP 如何从 Web 服务中获取内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34825641/