2

The company I work for decided to keep all the database queries in a RESTful API file. Was a big learning curve but finally I have the JSON object returning with the data. My problem now is how to populate the values into an HTML table.

Below I will show you what I have for now, what I already tried and the sample code, so you may suggest where I need to be corrected.

Thanks So much.

1. First, I request the data:

$schoolid = $_GET['schoolid'];
$data = file_get_contents("http://www.mydomainname.com/api/webapi.php?Oper=liststudents&schoolid=" . $schoolid);
echo $data;

2. And here's a sample of the results. Obviously A Json string:

{"data":[{
    "ID":"0450",
    "FirstName":"\u05d9\u05d5\u05e1\u05e3\u05de\u05e0\u05d7\u05dd",
    "LastName":"\u05d1\u05d9\u05e0\u05e0\u05e2\u05e8",
    "SchoolID":"17",
    "UID":"0001","
    TeacherID":"26"},{"ID":"0017",
    "FirstName":"\u05d0\u05e8\u05e8\u05d9\u05d9\u05e0\u05d3",
    "LastName":"\u05d6\u05d0\u05d1",
    "SchoolID":"17","UID":"0017",
    "TeacherID":"24"},{"ID":"0018",
    "FirstName":"\u05d3\u05d5\u05d1 \u05d2\u05dc\u05d5\u05d9\u05d1,
    "LastName":"\u05d9\u05e9\u05db\u05e8",
    "SchoolID":"17",
    "UID":"0018",
    "TeacherID":"24"}

I guess it's still an object that has to be parsed... So now,

3. Following is an illustration of what I'm trying to achieve.

|ID|  FirstNm  |  LastNm | School |UID| Teacher|      
|---|------------|-----------|-----------|-----|------------|     
|---|------------|-----------|-----------|-----|------------|

And so on, and so furth...

4. Here are some methods I tried so far but I either get "0" results, or it throws an error

A.

foreach($data->{'data'} as $obj){
    echo '<tr>
    <td>' . $obj->{'ID'} .'</td>
    <td>' . $obj->{'FirstName'} .'</td>
    <td>' . $obj->{'LastName'} .'</td>
    <td>' . $obj->{'SchoolID'} .'</td>
    <td>' . $obj->{'UID'} .'</td>
    <td>' . $obj->{'TeacherID'} .'</td>
</tr>'

B.

foreach ($data as $key => $jsons) {
    $table ='<table class="'.$jsons['class'].'" border="1">';
    foreach ($jsons as $rkey => $rvalue) {
        if($rkey=='head')
        {
            $table.='<tr>';
            foreach($rvalue as $rvv)
            {
                $table.='<th>'.$rvv.'</th>';
            }
            $table.='</tr>';
        }else
        if($rkey=='rows')
        {
            foreach($rvalue as $rvv)
            {
                $table.='<tr>';
                foreach($rvv as $rv)
                {
                    $table.='<td>'.$rv.'</td>';
                }
                $table.='</tr>';
            }
        }
    }
}
echo $table;

Tried few more things, but I only need ONE working model...

fusion3k
  • 11,568
  • 4
  • 25
  • 47
Rachel B
  • 57
  • 9
  • 2
    have you used the `json_decode()` function on the `$data` variable? – Derek Pollard Feb 11 '16 at 21:13
  • And what r u using for getting this array $data – devpro Feb 11 '16 at 21:14
  • @devpro in her question, she's using `file_get_contents()` – Derek Pollard Feb 11 '16 at 21:15
  • @oliver-queen no I am asking about the array not json string .. Like yur comments... Well dear OP r u using json_decode()???? – devpro Feb 11 '16 at 21:20
  • I did try using json_decode(), but then NOTHING appears in the results... not even before the foreach() loop – Rachel B Feb 11 '16 at 21:21
  • and this error you got is...? – Marc B Feb 11 '16 at 21:21
  • you should use `print_r()` on the `json_decode()`'d string – Derek Pollard Feb 11 '16 at 21:22
  • After using json_decode(); use print_r(); and the array structure u will get the idea how to use foreach loop suggestion... – devpro Feb 11 '16 at 21:23
  • Invalid JSON. check out this line `"FirstName":"\u05d3\u05d5\u05d1 \u05d2\u05dc\u05d5\u05d9\u05d1,` no end quote `"`. You can test it here: http://pro.jsonlint.com/ – CodeGodie Feb 11 '16 at 21:25
  • And I hope u knw the difference between json_decode($string,true) and json_decode($string) – devpro Feb 11 '16 at 21:25
  • @codegodie or maybe last backtick??? – devpro Feb 11 '16 at 21:27
  • @RachelB are you going to answer to any of our comments? Give some feedback – CodeGodie Feb 11 '16 at 21:32
  • You said it "throws errors". What errors does it throw and on what lines? – jjwdesign Feb 11 '16 at 21:38
  • Well, here's what's going... the name fields are entered in different languages.... ha ha.. I now have to figure out how to encode it properly... But I am so happy as I see for the first time the data coming in... quite a milestone.. atleast for me / / / As far as the missing quote the CodeGodie points out, probably my mistake when I copied the string into my question... sorry about that – Rachel B Feb 11 '16 at 21:44
  • Possible duplicate of [Parsing JSON file with PHP](http://stackoverflow.com/questions/4343596/parsing-json-file-with-php) – miken32 Feb 11 '16 at 23:12

2 Answers2

1

This is what I would do:

  1. fix your JSON. I think you posted it wrong

    $json = '{"data":[{"ID":"0450","FirstName":"\u05d9\u05d5\u05e1\u05e3\u05de\u05e0\u05d7\u05dd","LastName":"\u05d1\u05d9\u05e0\u05e0\u05e2\u05e8","SchoolID":"17","UID":"0001","TeacherID":"26"},{"ID":"0017","FirstName":"\u05d0\u05e8\u05e8\u05d9\u05d9\u05e0\u05d3","LastName":"\u05d6\u05d0\u05d1","SchoolID":"17","UID":"0017","TeacherID":"24"},{"ID":"0018","FirstName":"\u05d3\u05d5\u05d1 \u05d2\u05dc\u05d5\u05d9\u05d1","LastName":"\u05d9\u05e9\u05db\u05e8","SchoolID":"17","UID":"0018","TeacherID":"24"}]}';
    
  2. turn it into a PHP object with json_decode

    $obj = json_decode($json);
    
  3. use var_dump($obj) to debug, this will give you something like this:

    object(stdClass)[1]
      public 'data' => 
        array (size=3)
          0 => 
            object(stdClass)[2]
               public 'ID' => string '0450' (length=4)
               public 'FirstName' => string '×™×•×¡×£×ž× ×—×' (length=16)
               public 'LastName' => string '×‘×™× × ×¢×¨' (length=12)
               public 'SchoolID' => string '17' (length=2)
               public 'UID' => string '0001' (length=4)
               public 'TeacherID' => string '26' (length=2)
          1 => 
            object(stdClass)[3]
               public 'ID' => string '0017' (length=4)
               public 'FirstName' => string '××¨×¨×™×™× ×“' (length=14)
               public 'LastName' => string '×–×ב' (length=6)
               public 'SchoolID' => string '17' (length=2)
               public 'UID' => string '0017' (length=4)
               public 'TeacherID' => string '24' (length=2)
          2 => 
            object(stdClass)[4]
               public 'ID' => string '0018' (length=4)
               public 'FirstName' => string 'דוב גלויב' (length=17)
               public 'LastName' => string 'ישכר' (length=8)
               public 'SchoolID' => string '17' (length=2)
               public 'UID' => string '0018' (length=4)
               public 'TeacherID' => string '24' (length=2)
    
  4. Lastly, now that you see what you're working with, you can access the data using the -> object operator:

    foreach ($obj->data as $row) {
        var_dump($row->ID);
        var_dump($row->FirstName);
        var_dump($row->LastName);
        //...
    }
    
CodeGodie
  • 12,116
  • 6
  • 37
  • 66
-2

Something like this should work.

   <?php

   // Json_decode the file contents
   $file_data = json_decode(trim($file_text));
   // var_dump this $file_data and let us know what you get

   // Select the array potion 'data'
   $data = $file_data->data;
   // var_dump this $data and let us know what you get

    foreach ($data as $obj) {
       ...display code...
    }

    ?>

Throw in some var_dump() statements for the $file_data and $data to see if you are truly getting the data you expect. There may be some encoding/formatting issues with the way the data was stored. Do you know what processed and stored this data?

Concerning the encoding, I did a little research. If I'm not mistaken you have Unicode Entities that need to be converted to Unicode Text for display. iconv is great for conversion, but I'm not sure what the original encoding was. Was it Japanese writing?

$text = "\u05d0\u05e8\u05e8\u05d9\u05d9\u05e0\u05d3";

echo iconv('UCS-2BE', 'UTF-8', $text);

produces

屵〵搰屵〵攸屵〵攸屵〵搹屵〵搹屵〵攰屵〵搳

Or... try this from How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

$str = "\u05d0\u05e8\u05e8\u05d9\u05d9\u05e0\u05d3";

$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}, $str);
echo $str."\n\n";

Produces what looks like Hebrew characters:

ארריינד

If that's correct, write yourself a function to decode your data before display.

Community
  • 1
  • 1
jjwdesign
  • 3,272
  • 8
  • 41
  • 66
  • - no explanation as to why this works, what you did, or even why you did what you did. – Derek Pollard Feb 11 '16 at 21:24
  • I was trying to point out that we may be ignoring how the data is processed. Is it valid JSON? Does the data need to be trimmed or return characters removed from the end? Is the character encoding something other than UTF-8? – jjwdesign Feb 11 '16 at 21:32
  • Fabulous job jj !!!!! Neither do I know what exactly you suggested. In fact, It didn't work at first... then, I noticed and change the "$filetext" to "$json_string" which was the var I used. And walla... the table is all up... – Rachel B Feb 11 '16 at 21:33
  • 1
    I think the reason you got voted down is because this is not a suitable answer. its more of try this and try that.. more like a comment. – CodeGodie Feb 11 '16 at 21:33
  • I've always disliked comments when trying to show code changes. – jjwdesign Feb 11 '16 at 21:35
  • I agree. but its probably why the anal people here voted you down. Either way I think your answer solved it. – CodeGodie Feb 11 '16 at 21:37
  • @Rachel B, I think we've all been there. We focus on the complex and sometimes overlook the simple things. I'm glad you figured it out. BTW, excellent question with lots of detail. I up voted it. – jjwdesign Feb 11 '16 at 21:47
  • Thanks JJ, for both. The vote up, as well as your intuitive answer. The language issue is no resolved though as of yet. You don't expect the trim() to take care of that. Are you? – Rachel B Feb 11 '16 at 21:57
  • You should see some Hebrew characters if you use a proper `` in the html head. – Phil Feb 11 '16 at 22:09
  • @RachelB - I'm not sure what the original encoding was. iconv() is great to use and works very well. mb_convert_encoding() might also work well. You need to find out how it was encoded. – jjwdesign Feb 11 '16 at 22:52