Is there a JavaScript way to do file_get_contents()?

It's 2020 and some modern approach;

async function file_get_contents(uri, callback) {
    let res = await fetch(uri),
        ret = await res.text(); 
    return callback ? callback(ret) : ret; // a Promise() actually.
}

file_get_contents("https://httpbin.org/get", console.log);
// or
file_get_contents("https://httpbin.org/get").then(ret => console.log(ret));

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.


This function will return the file as a string just like the PHP file_get_contents().

function file_get_contents(uri, callback) {
    fetch(uri).then(res => res.text()).then(text => callback(text));
}

However unlike PHP, JavaScript will go on to the next statement, not waiting for the data to return.


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

Tags:

Javascript

Php