How PHP get the content from web service? How PHP get the content from web service? curl curl

How PHP get the content from web service?


This page contains dynamic content, loaded by JavaScript. You can see it in Google Chrome for example by access view-source:http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD.

If you look closer to the source code of the page (file http://server1-xeon.asuscomm.com/currency/JQuery/app_converter.js) you'll see, that it uses this code to get exchange data under the hood:

$.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 + ' ] ');        });

So, actually you can make such request in PHP to avoid access dynamic content on the http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD page.

UPD:I've added a more complete explanation.

enter image description here

By the time the page on http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD is loaded, a JavaScript code on this page (it means that it's executed on the client side, in a browser, not on your server) parses URL parameters and makes AJAX POST request to the URL http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx. It passes a JSON payload {amount:1.20,fromCurrency:'MYR',toCurrency:'SGD'} and gets a response like this {"d":0.390360}. So, you can just make a direct POST request to the http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx via curl, passing an amount, fromCurrency and toCurrency in JSON body and then decode received JSON response using json_decode($content);.


How data should look? Add this to your code from "UPDATED" and run:

$array["MYR"] = 1.2;$array["SGD"] = doubleval($obj->d)// Print simple array (print source for example)echo "<pre>";print_r($array);echo "</pre>";// Print true JSON-arrayprint_r(json_encode($array));

In web browser you will see:

Array(    [MYR] => 1.2    [SGD] => 0.39036){"MYR":1.2,"SGD":0.39036}

Can't understand your problem at this moment.

If you want print only returned value (digits), do it: echo $obj->d;