user3332475
user3332475

Reputation: 55

json to html table in php/javascript

i have a json file like this:

{
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 €",
signingDate: "28-02-2014"
},

i need to show it in a table like this:

<table>
            <tr>
                <td><strong>Data de publicação</strong></td>
                <td><strong>Empresa Contratada</strong></td>
                <td><strong>Empresa que Contratou</strong></td>
                <td><strong>ID</strong></td>
                <td><strong>Objecto adquirido</strong></td>
                <td><strong>Preço Contratual</strong></td>
                <td><strong>Data do Contrato</strong></td>
            </tr>
</table>

how i do it in PHP or javascript?

thank you very much people ;)

Upvotes: 0

Views: 12064

Answers (4)

Kristian Barrett
Kristian Barrett

Reputation: 3762

Here is a JSFiddle that shows how to print the data in your object:

http://jsfiddle.net/4PVr5/1/

And the code:

HTML

<table id="table">
    <tr>

    </tr>
</table>

JAVASCRIPT

var object = {
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014"
};
for (var prop in object) {
      // important check that this is objects own property 
      // not from prototype prop inherited
      if(object.hasOwnProperty(prop)){
          var td = document.createElement("td");
          var strong = document.createElement("strong");
          var text = document.createTextNode(prop + " - " + object[prop]);
          strong.appendChild(text);
          td.appendChild(strong);
          document.getElementById("table").appendChild(td);
      }
   }

EDIT UPDATE TO angus_thermopylae:

I have updated the JSFiddle to show the concept: http://jsfiddle.net/4PVr5/12/

Then you can have as many properties on the object you want but only print the ones you defined and in the order you defined. You just add a text string and then you got another print.

EDIT UPDATE: I updated the code to follow the table headers. Now it adds them directly and also handles objects with too few properties.

HTML

<table id="table">
    <thead>
        <th id="publicationDate"></th>
        <th id="contracted"></th>
        <th id="contracting"></th>
        <th id="id"></th>
        <th id="objectBriefDescription"></th>
        <th id="initialContractualPrice"></th>
        <th id="signingDate"></th>
    </thead>
    <tbody>

    </tbody>
</table>

JAVASCRIPT

var orderedObject = {
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014"
};

var unorderedObject = {
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014",
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
};

var toManyPropertiesObject = {
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014",
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
    newProp: "ignored",
    newProp1: "ignored",
    newProp2: "ignored",
};


var toFewPropertiesObject = {
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
};

printObjectInTable(orderedObject, "table");
printObjectInTable(unorderedObject, "table");
printObjectInTable(toManyPropertiesObject, "table");
printObjectInTable(toFewPropertiesObject, "table");

function printObjectInTable(objectToIterate, tableID) {
    var thChildren = document.getElementById(tableID).getElementsByTagName("th"),
        childrenLength = thChildren.length,
        tr = document.createElement("tr");
    for (var i = 0; i < thChildren.length; i++) {
        var th = thChildren[i];
        // important check that this is objects own property 
        // not from prototype prop inherited
        var td = document.createElement("td");
        if (objectToIterate.hasOwnProperty(th.id)) {
            td.appendChild(document.createTextNode(objectToIterate[th.id]));
        }
        tr.appendChild(td);
    }
    document.getElementById(tableID).getElementsByTagName("tbody")[0].appendChild(tr);
}

Upvotes: 1

Suman Bogati
Suman Bogati

Reputation: 6349

Accoding to your answer on comment, you are using

$('table#tbl TBODY').append(

for append the data into table,

But you should use

$('table#tbl').append(

Other code is fine

Also you have to run your code into web server.

Upvotes: 0

meda
meda

Reputation: 45500

Here is how you can do it in PHP:

$json=file_get_contents("http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)");
$data =  json_decode($json);

//var_dump($data);
echo "<table>
           <tr>
                <td><strong>Data de publicação</strong></td>
                <td><strong>Empresa Contratada</strong></td>
                <td><strong>Empresa que Contratou</strong></td>
                <td><strong>ID</strong></td>
                <td><strong>Objecto adquirido</strong></td>
                <td><strong>Preço Contratual</strong></td>
                <td><strong>Data do Contrato</strong></td>
            </tr>";

foreach($data as $object):?>

           <tr>
                <td><strong><?php echo $object->{'publicationDate'}?></strong></td>
                <td><strong><?php echo $object->{'contracted'}?></strong></td>
                <td><strong><?php echo $object->{'contracting'}?></strong></td>
                <td><strong><?php echo $object->{'id'}?></strong></td>
                <td><strong><?php echo $object->{'objectBriefDescription'}?></strong></td>
                <td><strong><?php echo $object->{'initialContractualPrice'}?></strong></td>
                <td><strong><?php echo $object->{'signingDate'}?></strong></td>
            </tr>

<?php endforeach;
      echo "</table>";
?>

DEMO

Upvotes: 1

angus_thermopylae
angus_thermopylae

Reputation: 151

A per-row conversion will work something like this (low level and not doing anything fancy):

//with jdata as the object below
{
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 €",
signingDate: "28-02-2014"
}

function tablize(jdata) {
    var trow = "<tr>";
    trow += "<td>"+jdata.publicationData+"</td>";
    trow += "<td>"+jdata.contracted+"</td>";
    trow += "<td>"+jdata.contracting+"</td>";
    trow += "<td>"+jdata.id+"</td>";
    trow += "<td>"+jdata.objectBriefDescription+"</td>";
    trow += "<td>"+jdata.initialContractualPrice+"</td>";
    trow += "<td>"+jdata.signingDate+"</td>";
    trow += "</tr>"
    return trow;
}

Now your issue is getting it in the table. Assuming you have the ability to adjust (slightly) the table structure, I would recommend setting up your table like so:

<table>
    <thead>
        <tr>
            <th><strong>Data de publicação</strong></th>
            <th><strong>Empresa Contratada</strong></th>
            <th><strong>Empresa que Contratou</strong></th>
            <th><strong>ID</strong></th>
            <th><strong>Objecto adquirido</strong></th>
            <th><strong>Preço Contratual</strong></th>
            <th><strong>Data do Contrato</strong></th>
        </tr>
    </thead>
    <tbody id="cdata"></tbody>
</table>

Then, you just need a function to either iterate through all the data and add the accumulated rows, or append the newly created row to the element:

Assuming you'll get this data as an array:

function fillTable(contractarray) {
    var tblrows = "";
    if (contractarray) {
        for (var i=0;i<contractarray.length;i++) {
            tblrows += tablize(contractarray[i]);
        }
    }
    //appropriate method to set the table body--using jQuery for brevity
    $("#cdata").html(tblrows);
}

If you don't have the ability to adjust the table html, then you'll have to "find" the table in the DOM structure another way and either recreate the entire thing (headers included) or adjust it by clearing/adding rows appropriately.

Either way, the tablize(jdata) function will work, and the second function will need to be adjusted accordingly.

To pull it altogether (with the url that the requestor supplied:

var dataurl = "http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)";

$.getJSON(dataurl, function(data) { tablize(data)});

That kicks off the request, passes the data to the tablize() function, and fills the rows. A small (but good) side effect is that if no data is returned, the table empties, showing that we got nothing back.

Upvotes: 0

Related Questions