Use PHP functions in JavaScript
Logged in as Guest

Work in progress

This is our new site. Many features do not work yet. You should probably go to Kevin's TechBlog », where active PHP.JS development still takes place.

Javascript file_get_contents

Read the entire file into a string

function file_get_contents( url ) {
    // Read the entire file into a string  
    // 
    // version: 812.316
    // discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_file_get_contents

    // +   original by: Legaev Andrey
    // +      input by: Jani Hartikainen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes. 
    // %        note 1: To avoid browser blocking issues's consider using jQuery's: $('#divId').load('http://url') instead.
    // *     example 1: file_get_contents('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'
    var req = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) throw new Error('XMLHttpRequest not supported');
    
    req.open("GET", url, false);
    req.send(null);
    
    return req.responseText;
}

Examples

Example 1

Running

file_get_contents('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');

Could return

'123'

Dependencies

No dependencies, you can use this function standalone.

Thank you

Improve/Comment this

Comment

Code


Contribute a New function

More functions

In this category

basename
dirname
file
file_exists
file_get_contents
filesize

Download

To include all PHP.JS functions at once, you need one of the following packages. The normal packages are just a collection of standalone functions, making it easy to address them. With the namespaced packages, the functions are contained in one object. Making it easier to avoid naming conficts and to extend, overrule, or modify PHP.JS to your own whishes.

Normal (novice)

Namespaced (advanced)

Who uses PHP.JS

  • vanzonneveld.net

Do you use PHP.JS? contact us and get linked!