0

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 ;)

11
  • it's as an object you provided not json. Commented Mar 1, 2014 at 19:43
  • is a file like this:base.gov.pt/base2/rest/contratos?&sort(-publicationDate) Commented Mar 1, 2014 at 19:46
  • the content on file you provide is json indeed. Commented Mar 1, 2014 at 19:47
  • you can help me to show it on table? thank you Commented Mar 1, 2014 at 19:48
  • Do you want to show value of object into td something like "28-02-2014", "Servicash - Equipamentos Electrónicos, Lda.", "Banco de Portugal", please make me correct if i am wrong. Commented Mar 1, 2014 at 19:50

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

8 Comments

$json is variable of what? i don't understand sorry
@user3332475 $json=file_get_contents("base.gov.pt/base2/rest/…); sorry I updated
and the variable $object is what?... i'm new in php sorry
because i do it and show this error: Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\base2\index.php on line 27
You have to run this on webserver.
|
1

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);
}

7 Comments

I actually like your solution better--much more general. Assuming that the object is coming from another source, how would you ensure that the order of the properties is correct? (Or, if they add a property, that the table doesn't go off kilter?)
You could add a method that checks how many properties it has. And add a sort to the table based on what the property name is. After that run through the object and insert the TDs. Hope this makes sense.
It does--for these kinds of tablizing, I usually make a version of the one in my solution, but I'm always looking for ways to generalize. Less rework that way.
@angus_thermopylae see the updated answer and fiddle.
Very nice! I was thinking that you would need a property list, but I've not used that means of getting individual properties (knew about it, never really needed it). I bet if you passed in the array of property names, you could reuse this throughout a web app for a bunch of different tables.
|
0

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.

5 Comments

i need to work just in a php file because the json file have a lote of data
is like this the json file:
There are a lot of good possibilities here--it mostly depends upon how comfortable with javascript you are, and on whether you want to do the work client side or server side.
i just do it on localhost to test it
Sorry--by "client side" I meant having the user's browser do all the work, and by "server side" I meant having the php deliver the data already formatted.
0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.