19

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?

CS_2013
  • 1,158
  • 3
  • 13
  • 24

9 Answers9

10

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));
Kerem
  • 11,377
  • 5
  • 59
  • 58
9

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.

PitaJ
  • 12,969
  • 6
  • 36
  • 55
8

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

Sampson
  • 265,109
  • 74
  • 539
  • 565
7

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.

Kerem
  • 11,377
  • 5
  • 59
  • 58
Steve Lage
  • 692
  • 6
  • 11
  • 4
    Based on the domain/URL of your link(s) being the same as, or containing, your user name, you appear to have linked to your own site/a site you're affiliated with. If you do, you *must disclose that it's your site*. If you don't disclose affiliation, it's considered spam. See: [**What signifies "Good" self promotion?**](//meta.stackexchange.com/q/182212) and [the help center on self-promotion](//stackoverflow.com/help/promotion). Disclosure must be explicit, but doesn't need to be formal. When it's your own *personal* content, it can just be something like "on my site…", "on my blog…", etc. – Makyen Apr 17 '19 at 21:50
3

Not in a general sense. Cross-domain restrictions disallow Javascript code from doing this.

If the target site has CORS (cross-origin resource sharing) set up, you can use XMLHttpRequest to load files. Most sites do not, as it's off by default for security reasons, and is rarely necessary.

If you just need to include an HTML page, you can stick it in an <iframe> element. This is subject to some layout gotchas, though (the page ends up in a fixed-size element).

  • ...can I do any analysis of the iframe...maybe grab the title some how? – CS_2013 May 21 '12 at 22:41
  • @CS_2013 No, not if the `iframe` isn't a document from your domain. – Sampson May 21 '12 at 22:41
  • Nope. The contents of the frame are pretty much completely off-limits. –  May 21 '12 at 22:42
  • No. Cross-domain resource sharing is set up the way it is for very good security reasons. Read Michal Zalewski's excellent book "The Tangled Web: A Guide to Securing Modern Web Applications" for details. –  May 21 '12 at 22:43
  • Well...it needs to be ammended...because I'm taking up more network resources now...adding another hop...yet still getting the data I intended to get....keep the security...kill the inefficiency. – CS_2013 May 21 '12 at 22:47
  • Got to wonder how many billions of page requests this creates per day, month, etc. on the web. – CS_2013 May 21 '12 at 22:50
  • @CS_2013: How would you "keep the security"? I think you are misunderstanding the problem at a very fundamental point. – Niklas B. May 21 '12 at 23:12
2

Or You can use php.js library. Which allow some php functions for javascript. file_get_contents() function one of them.

<script>
var data = file_get_contents('Your URL');
</script>

You can find more info about php.js : http://phpjs.org/

Fazle Elahee
  • 599
  • 3
  • 14
0

I think this may be useful for you:

An npm package with the "file-get-contents" method for node.js https://www.npmjs.com/package/file-get-contents

It is asynchronous so if you are using express it should be used like this

app.get('/',  async (req, res)=>{
    //paste here the code below
}

Example

const fileGetContents = require('file-get-contents');
 
// A File request
 
try {
    let data = await fileGetContents('/tmp/foo/bar');
 
    console.log(data);
} catch (err) {
    console.log('Unable to load data from /tmp/foo/bar');
}
 
// Or a HTTP(S) request
 
fileGetContents('https://pokeapi.co/api/v2/pokemon/1/').then(json => {
    const pokemon = JSON.parse(json);
 
    console.log(`Name of first pokemon is ${pokemon.name}`);
}).catch(err => {
    console.err(`Unable to get content from PokeAPI. Reason: ${err.message}`);
});
Faig
  • 33
  • 10
-1
  <div id="svg">

  </div>
  <script>

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

            var xmlSvg =text;
            console.log(xmlSvg );
            document.getElementById('svg').innerHTML = xmlSvg;
        })
    }

    
    var uri ='You-urlllllllll-svg';

    file_get_contents(uri);

</script>
  • Can you add clarification around this answer? Thank you! – 10 Rep May 06 '21 at 22:44
  • Welcome to stackoverflow! Please explain your answer to make it helpful. https://stackoverflow.com/help/how-to-answer https://stackoverflow.com/tour – ethry Oct 04 '22 at 02:23
-1

function file_get_contents(filename) {
    fetch(filename).then((resp) => resp.text()).then(function(data) {
        document.getElementById("id").innerHTML = data;
    });
}
file_get_contents("url");
<span id="id"></span>