1

How to pass an array from .php file to .html file ?

   <?php 
       $arr= array(
            "first_name" => "Darian",
            "last_name" => "Brown",
            "age" => "28",
            "email" => "[email protected]"
    );
   ?>

i have a .html file and i want to send my result from my .php file to .html file for further usage.

1
  • In the html file, use AJAX to call php file and get the result. Nov 23, 2012 at 3:50

2 Answers 2

2

HTML by itself doesn't do processing and can't handle arrays.

You have two options, if it's at page creation, insert a php snippet that takes the array and generates appropriate HTML.

If it's after the page has been drawn, use a framework like jQuery or JavaScript to get the array from the php file (learn about JSON in this case, it will facilitate the work, see documentation here) and then modify the DOM accordingly.

For example, if your script is accessed through AJAX (like jQuery), you could do something like:

<?php 
    $list = array( array('user_1', 1, 'continue'),
        array('user_2', 2 , '
        array('user_1', 3 , 'finish') 
    ); 
    echo json_encode($list);    
?>
6
  • is tat possible to carry out this transfer by this ? xmlhttp.open("GET","myphp.php",true); xmlhttp.send();
    – jc_tan
    Nov 23, 2012 at 8:40
  • @jc_tan yes, and you would receive the content in xmlhttp.responseText
    – emartel
    Nov 23, 2012 at 8:55
  • emartel, may i know how can i bring a variable from <?php ?> to <script></script> ?
    – jc_tan
    Nov 23, 2012 at 9:26
  • You probably should json_encode your array and then echo it in PHP. Then, in JavaScript, I strongly suggest you take a look at jQuery and use getJSON - api.jquery.com/jQuery.getJSON
    – emartel
    Nov 23, 2012 at 9:38
  • $(document).ready(function(){ $.getJSON('array.php', function(data) { $.each(data, function(key, val) { $('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + ' ' + val.age + '</li>'); }); }); }); i cant access to it, it is due to the location ?
    – jc_tan
    Nov 24, 2012 at 8:09
0

You cannot include the array result in an html file. Both the files have to be php. You can find more info on adding them in a php file here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.