Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a JavaScript way to do file_get_contents()?

Tags:

javascript

php

Here is the PHP documentation

Here is how I would use it in an Ajax call, if I don't find a pure client way to do this.

$homepage = file_get_contents('http://www.example.com/');
echo $homepage;

Is there way to do this client side instead so I don't have to ajax the string over?

like image 869
CS_2013 Avatar asked May 21 '12 22:05

CS_2013


People also ask

What will the file_get_contents () return?

The function returns the read data or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

What is the function file_get_contents () useful for?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string.


2 Answers

you could do

JS code:

$.post('phppage.php', { url: url }, function(data) {
    document.getElementById('somediv').innerHTML = data;        
});

PHP code:

$url = $_POST['url'];
echo file_get_contents($url);

That would get you the contents of the url.

like image 194
PitaJ Avatar answered Sep 25 '22 22:09

PitaJ


JavaScript cannot go out and scrape data off of pages. It can make a call to a local PHP script that then goes on its behalf and grabs the data, but JavaScript (in the browser) cannot do this.

$.post("/localScript.php", { srcToGet: 'http://example.com' }, function(data){
  /* From within here, data is whatever your local script sent back to us */
});

You have options like JSONP and Cross-Origin Resource Sharing at your disposal, but both of those require setting up the other end, so you cannot just choose a domain and start firing off requests for data.

Further Reading: Same origin policy

like image 39
Sampson Avatar answered Sep 25 '22 22:09

Sampson