I want to use PHP to simultaneously download data from 2 URLs via simplexml_load_file but the script must wait until all data is gathered before going ahead processing the rest of the code.
$url1 = "http://www.example.com/api1";
$request1 = simplexml_load_file($url1);
$url2 = 'http://www.example.com/api2';
$request2 = simplexml_load_file("compress.zlib://$url2", NULL, TRUE);
echo 'finished';
I want all data is completely downloaded before printing the word finished.
How would you edit the script above to accomplish that?
Fetching URLs directly while opening "files" with functions such as simplexml_load_file is intended as a short-cut for simple cases where you don't need things like non-blocking / asynchronous I/O.
Your script as written will wait for everything to download before printing the word "finished", but it will also wait for the response from http://www.example.com/api1 to finish downloading before starting the request to http://www.example.com/api2.
You will need to break your problem down:
Download the contents of two URLs, in parallel (or more accurately "asynchronously"). Your result will be two strings.
Parse each of those strings using simplexml_load_string.
The most popular HTTP library for PHP is Guzzle, but you should be able to find many alternatives, and guides to writing your own using the built-in cURL functions if you search for terms like "PHP asynchronous HTTP" or "PHP parallel HTTP requests".
I'm trying very simple in PHP and not very sure what to search here or on google.
Problem is -
In PHP function I want to call/get a URL
http://www.example.com/message?Name=MyNameIsX
and like to read the return value (body) at this URL (which may contain "Your Name is MyNameIsX")
I tried
$data = file_get_contents($url)
This is timing out; although I'm able to open the $url in the browser.
Yes, file_get_contents normal use for files on this server and base on support and setting this perhaps is not allow.
See PHP CUrl http://php.net/manual/en/curl.examples.php or example
http://php.net/manual/en/curl.examples.php, http://php.net/manual/en/curl.examples-basic.php
You could use cUrl as suggested by FIG-GHD742 but I find the HTTP extension a lot easier to use. It's newer and has a neat OOP api.
Another method is that you can actually do an include/require with these, but it's generally a bad idea to do so if you don't control the source from which the data is coming
It sounds like you need to enable loopback calls on the server (self-calls). It would be better to get the data on the backend if you need it on the same server. Via a PHP API or calls to a database.
**
This will help you lot : http://php.net/manual/en/curl.examples.php
http://php.net/manual/en/curl.examples.php,
http://php.net/manual/en/curl.examples-basic.php
**
Yes the above answers is right. some hosting providers disable it for security purpose. You may also try fopen(php) if you are not looking for Curl way. Read documentation here http://php.net/manual/en/function.fopen.php
I know AJAX will not be what it is called, but I am looking for something similar that can be done from within PHP itself (not using javascript).
Basically, as the PHP is creating the page, I want to query an API to gather some information that will be used on the current page. Is this possible, and if so what would be the best method?
Thanks
You can use fopen or curl:
Here is an example to open a connection to twitters API, read the public timeline and output parts of it.
<?php
$fp = fopen("http://api.twitter.com/1/statuses/public_timeline.json?count=3&include_entities=false","r");
while($data = fgets($fp))
{
$json .= $data;
}
$arr = json_decode($json);
print_r($arr);
?>
You are probably wanting curl.
http://php.net/manual/en/book.curl.php
If you're talking about a remote HTTP API, you would utilize cURL at runtime. It's basically PHP's way of accessing information across domains.
The above can be a little overwhelming - check out the simple example page to get you started. If available, I suggest working with cURL from the command line, as there's quite a few options on there. It's a good way to get familiar with the command and different options available.
i need to do a "file_get_contents" on a URL and there has to be data posted to the url before the contents are retrieved. is this possible? maybe something like
$contents = file_get_contents($_POST"http://www.example.com/");
so that i can then work with the $contents variable?
You cannot*** POST data using file_get_contents, you must use something like cURL
* I mark this because it is actually possible taking advantage of the third parameter which uses http context(see example one). However it really isn't worth your trouble if you have something like cURL.
Ah, I have tried to do this. Simply put you can't unless you install new extra software on your sever and go through A LOT of hassel and server load.
Best bet is to use GET if at all possible!
:)
Basically i want this json output to be transferred to my server/php.
i try this
$url="http://maps.google.com/maps/nav?q=from:9500 wil to:3000 bern";
$conte = file_get_contents($url);
echo $conte;
the json is not echo, how can i save the output to my server?
You need to urlencode the GET parameters:
echo file_get_contents('http://maps.google.com/maps/nav?q=from:9500%20wil%20to:3000%20bern');
# Returns
# {"name":"from:9500 wil to:3000 bern","Status":{"code":200,"request":"directions"},"Placemark":[{"id":"","address":"Wil, Switzerland","AddressDetails":{"Country":{"CountryNameCode":"CH","CountryName":"Schweiz","AdministrativeArea":{"AdministrativeAreaName":"St. Gallen","SubAdministrativeArea":{"SubAdministrativeAreaName":"Wil","Locality":{"LocalityName":"Wil"}}}},"Accuracy": 4},"Point":{"coordinates":[9.048081,47.463817,0]}},{"id":"","address":"Frohbergweg 7, 3012 Bern District, Switzerland","AddressDetails":{"Country":{"CountryNameCode":"CH","AdministrativeArea":{"AdministrativeAreaName":"BE","SubAdministrativeArea":{"SubAdministrativeAreaName":"Bern","Locality":{"LocalityName":"Bern District","DependentLocality":{"DependentLocalityName":"Länggasse-Felsenau","Thoroughfare":{"ThoroughfareName":"Frohbergweg 7"},"PostalCode":{"PostalCodeNumber":"3012"}}}}}},"Accuracy": 0},"Point":{"coordinates":[7.436386,46.954897,0]}}],"Directions":{"copyrightsHtml":"Map data \u0026#169;2010 Google, Tele Atlas ","summaryHtml":"178\u0026nbsp;km (about 2 hours 2 mins)","Distance":{"meters":177791,"html":"178\u0026nbsp;km"},"Duration":{"seconds":7343,"html":"2 hours 2 mins"},"Routes":[{"Distance":{"meters":177791,"html":"178\u0026nbsp;km"},"Duration":{"seconds":7343,"html":"2 hours 2 mins"},"summaryHtml":"178\u0026nbsp;km (about 2 hours 2 mins)","Steps":[{"descriptionHtml":"Head \u003Cb\u003Esouth\u003C\/b\u003E on \u003Cb\u003EToggenburgerstrasse\u003C\/b\u003E toward \u003Cb\u003ELerchenfeldstrasse\/\u003Cwbr\/\u003ERoute 16\/\u003Cwbr\/\u003ERoute 7\u003C\/b\u003E","Distance":{"meters":29,"html":"29\u0026nbsp;m"},"Duration":{"seconds":2,"html":"2 secs"},"Point":{"coordinates":[9.048030,47.463830,0]}},{"descriptionHtml":"Take the 1st left onto \u003Cb\u003ERoute 7\u003C\/b\u003E","Distance":{"meters":625,"html":"650\u0026nbsp;m"},"Duration":{"seconds":109,"html":"2 mins"},"Point":{"coordinates":[9.047930,47.463570,0]}},{"descriptionHtml":"At the traffic circle, take the \u003Cb\u003E1st\u003C\/b\u003E exit onto \u003Cb\u003EGeorg Rennerstrasse\u003C\/b\u003E","Distance":{"meters":871,"html":"850\u0026nbsp;m"},"Duration":{"seconds":77,"html":"1 min"},"Point":{"coordinates":[9.056170,47.463110,0]}},{"descriptionHtml":"Take the ramp to \u003Cb\u003EZürich\/\u003Cwbr\/\u003EFrauenfeld\u003C\/b\u003E","Distance":{"meters":330,"html":"350\u0026nbsp;m"},"Duration":{"seconds":22,"html":"22 secs"},"Point":{"coordinates":[9.053350,47.455800,0]}},{"descriptionHtml":"Merge onto \u003Cb\u003EA1\u003C\/b\u003E\u003Cdiv class=\"google_impnote\"\u003EToll road\u003C\/div\u003E","Distance":{"meters":173696,"html":"174\u0026nbsp;km"},"Duration":{"seconds":6790,"html":"1 hour 53 mins"},"Point":{"coordinates":[9.050270,47.453900,0]}},{"descriptionHtml":"Take exit \u003Cb\u003E36-Bern-Neufeld\u003C\/b\u003E toward \u003Cb\u003EBremgarten\u003C\/b\u003E","Distance":{"meters":579,"html":"600\u0026nbsp;m"},"Duration":{"seconds":33,"html":"33 secs"},"Point":{"coordinates":[7.436980,46.966570,0]}},{"descriptionHtml":"At the traffic circle, take the \u003Cb\u003E2nd\u003C\/b\u003E exit onto \u003Cb\u003ENeubrückstrasse\u003C\/b\u003E","Distance":{"meters":1357,"html":"1.4\u0026nbsp;km"},"Duration":{"seconds":243,"html":"4 mins"},"Point":{"coordinates":[7.429580,46.966790,0]}},{"descriptionHtml":"Turn right at \u003Cb\u003EMittelstrasse\u003C\/b\u003E","Distance":{"meters":146,"html":"150\u0026nbsp;m"},"Duration":{"seconds":24,"html":"24 secs"},"Point":{"coordinates":[7.437750,46.956720,0]}},{"descriptionHtml":"Take the 1st left onto \u003Cb\u003EBrückfeldstrasse\u003C\/b\u003E","Distance":{"meters":104,"html":"100\u0026nbsp;m"},"Duration":{"seconds":33,"html":"33 secs"},"Point":{"coordinates":[7.436060,46.956100,0]}},{"descriptionHtml":"Take the 1st right onto \u003Cb\u003EFrohbergweg\u003C\/b\u003E\u003Cdiv class=\"google_note\"\u003EDestination will be on the left\u003C\/div\u003E","Distance":{"meters":54,"html":"54\u0026nbsp;m"},"Duration":{"seconds":10,"html":"10 secs"},"Point":{"coordinates":[7.436830,46.955320,0]}}],"End":{"coordinates":[7.436234,46.955057,0]}}]}}
How do you want to save it? As a file?
If you can open via file_get_contents(), then URL opening for fopen() wrappers is on.
Then you can just do...
$url = 'http://maps.google.com/maps/nav?q=from:9500 wil to:3000 bern';
$content = file_get_contents($url);
file_put_contents('google-map-json.txt', $content);
You can get that into a usable object in PHP with json_decode().
You may want to do that if you want to save it to your database.
If you don't want to overwrite the file each time, you could generate a random hash of the response for the filename, or something similar.
Update
sorry my bad. i know how to save file. but the json is not even echoed through file_get_contents.
You may not have URL fopen() wrappers enabled.
You can find out by running this...
var_dump(ini_get('allow_url_fopen'));
If it is disabled, and you can't or don't want to turn it on, you can use cURL (if you have that library installed).
Update
When I tried to access the page via file_get_contents(), I got...
HTTP/1.0 400 Bad Request
You may need to use cURL, and mimic a browser (user agent etc).
Or you can set
ini_set('user_agent', 'Mozilla or something');
And then use file_get_contents().
Update
I tried with cURL too, and it didn't work :(
I think the next step is to examine all the headers your browser sends (when it works), and then send the equivalent via cURL.
Update
I noticed the Markdown editor wasn't liking the URL (see my OP's edit), and it dawned me - urlencode() the GET params!
You can write the data to a file using PHP's IO functions
$fp = fopen('data.txt', 'a');
fwrite($fp, $conte);
fclose($fp);
You can use json_decode to parse the data from the file_get_contents() variable. (I would personally use cURL instead of file_get_contents()).