json to php (server) possible and how? - php
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()).
Related
Parallel downloads using simplexml_load_file in PHP
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".
Get all content with file_get_contents()
I'm trying to retrieve an webpage that has XML data using file_get_contents(). $get_url_report = 'https://...'; // GET URL $str = file_get_contents($get_url_report); The problem is that file_get_contents gets only the secure content of the page and returns only some strings without the XML. In Windows IE, if I type in $get_url_report, it would warn it if I want to display everything. If I click yes, then it shows me the XML, which is what I want to store in $str. Any ideas on how to retrieve the XML data into a string from the webpage $get_url_report?
You should already be getting the pure XML if the URL is correct. If you're having trouble, perhaps the URL is expecting you to be logged in or something similar. Use a var_dump($str) and then view source on that page to see what you get back. Either way, there is no magic way to get any linked content from the XML. All you would get is the XML itself and would need further PHP code to process and get any links/images/data from it.
Verify if openssl is enable on your php, a good exemple of how to do it: How to get file_get_contents() to work with HTTPS?
using file get contents on a url that requires post data
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! :)
Why does fopen produce varying files from calls to Twitter, when the file should be static?
I am trying to get a list of Twitter users using their API. When I query the API in my browser (http://api.twitter.com/1/statuses/followers.xml?screen_name=atomictom), it returns an XML doc with 100 users, as it should. However, when performing the query from my php file: $file=fopen("http://api.twitter.com/1/statuses/followers.xml?screen_name=atomictom", "r"); $xmlString=fread($file,13421772); fclose($file); echo $xmlString; it only returns 1, and sometimes 2 users. It actually varies when I refresh! Any ideas on why this would happen? I suspect a problem with fopen or fread. Unfortunately, in fread I cannot use filesize($file), as it is a resource and not a string. Thank you so much for your help!
You could use file_get_contents() instead. There is no need to pass a file size arg to it, and it will work well if you have allow_url_fopen = On set in your php.ini file. <?php echo file_get_contents("http://api.twitter.com/1/statuses/followers.xml?screen_name=atomictom"); ?>
Are you sure your PHP code is logged in? It seems likely that when you try it from the browser, it's using your own logged in cookie, but your PHP code doesn't have access to that.
How to retrieve http page from another host server with php and detect redirect
Let's say I have a server at www.myhost.com. From there by using php I want to retrieve the html document that the php file www.anotherhost.com/somefile.php produces. I also want to use php to do this. anotherhost is not on the same server as myhost. I know that functions such as fopen, f_get_contents and file can do this by simply executing e.g. $fp = fopen ("http://www.anotherhost.com/somefile.php") and from there fp can be used as any other file pointer to read the contents. BUT, for some reason I also want to know if somefile.php at anotherhost ordered a client-side redirect when I tried to retrieve somefile.php´s resulting html document. somefile.php can do this by header ("Location: http://www.anotherhost.com/extrafile.php") Now fopen will retrieve the html document that extrafile.php produces, without detecting that a client-side redirect has been performed. Is there some functionality in PHP that enables you to retrieve html documents from other servers AND notifies you if a redirect has taken place? It is acceptable if I must follow the redirect by myself (not done automatically), as long as I'm told what the new URL is. Executing arbitrary commands with the function system is not preferred. PS. If you are going to suggest fsockopen, then please explain why i get the error "Unable to find the socket transport "http" - did you forget to enable it when you configured PHP?" when I try to execute fsockopen ("http://localhost") and I also get "Failed to parse address "localhost" when I do fsockopen ("localhost") Thanks for reading. Help would be greatly appreciated.
You can use the Zend_Http_Client from Zend Framework. It has methods for retrieving the number of redirects as well as setting a limit to the number of redirects to follow etc. If you just want to know how it's done, then you can look into the source code and try to figure it out. Shouldn't be too hard I think.
I would use cURL for this. If the redirect is specified in the header, instead of apache mod_rewrite for example, then you should be able to detect if a redirect is present by grabbing all of the headers sent by the response. Optionally, there is a setting to automatically follow the redirect (http://us.php.net/manual/en/function.curl-setopt.php).
As of php 5.2 you can use the stream api and a stream_notification_callback e.g. function notification($code, $severity, $message, $mcode, $transferred, $max) { if ( STREAM_NOTIFY_REDIRECTED===$code ) { echo 'redirected to ', $message, "\n"; } } $ctx = stream_context_create(null, array('notification' => 'notification')); $c = file_get_contents("http://spiegel.de", false, $ctx); echo 'len=', strlen($c); prints redirected to http://www.spiegel.de/ len=144446
You probably want a full HTTP client, not stream wrappers and fopen()/file_get_contents(). I think its possible to do what you want with stream wrappers using stream_get_meta_data() but you would be better off with a fuller implementation.
If you don't want to go down the Zend or stream route, you could always use the cURL functions. These will let you return the headers, hence you could analyse these to ascertain whether any re-directs are being issued. (You can also use the 'CURLOPT_MAXREDIRS' option to specify that it shouldn't follow re-directs.)