Possible Duplicate:
Can Javascript read the source of any web page?
I want to download a file using javascript and parse it. I need a function like php's file_get_contents()
. I looked for it, but I couldn't find anything.
Update: Thanks for solutions, but I forgot to write that AJAX doesn't suite this problem, because I don't have any access to the remote address and have cross-domain requesting problem. I can't setup any php proxy either, because my host blocks access to fopen. I would prefer a pure javascript solution.
PS: Sorry, but the question was really a duplicate (I didn't know that) and the solution provided here perfectly suits this problem.
Select View Page Source to show the web page's code. Copy the entire code by highlighting all or just the specific area of code that you want, pressing Ctrl+C or Command+C on your keyboard and then paste the code into a text or document file.
Look into the XMLHttp Request
http://www.w3schools.com/xml/xml_http.asp
or the load, $.get, $.post and $.ajax methods of JQuery.Here is a sample
var request = new XMLHttpRequest();
request.open("GET", 'http://www.url.com');
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
//response handling code
}
};
request.send(null); // Send the request now
Short question, short answer: You probably want to play around with some Ajax. Either by calling a local php script making a file_get_contents()
and returning it the the page, or directly calling an external URL. Your browser might not allow you to do this though.
Added:
You updated your question saying you prefer a pure javascript solution. I don't think you can since you're trying to fetch something that is not JSONP.
Also, you say your host blocks fopen()
, I used to be on a hosting where they did the same. I was surprised to find they did NOT block the use of sockets, here's my workaround:
$server = "www.example.com";
$path = "/path/index.html";
$type = "HTTP/1.1";
$fp = fsockopen($server, 80, $errno, $errstr, 30);
if (!$fp) echo "$errstr ($errno)<br />\n";
else {
$out = "GET $path $type\r\n";
$out .= "Host: $server\r\n";
$out .= "User-Agent: Mozilla 4.0\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
$contents = "";
while (!feof($fp)) $contents .= fgets($fp, 128);
fclose($fp);
echo $contents;
}
I realize you didn't want a PHP proxy solution, I think you might have no other choice. Give it a try, works great for me. If your hosting also is blocking fsockopen()
you might be out of luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With