Hi I am trying to read a nested JSON array data into a table and as a list not just in a line.
Look, at the way it comes out:
Link to JSON: JSON
L: demo
P: ocfB6XzF73
Documentation: URL-DOC
JSON code I am trying to reach:
"EquipmentList": [ "ABSBrakes", "Alarm", "AlloyRims", "AntiSpin", "AutomaticGear", "RemoteCentralLocking", "PoweredWindows", "PoweredMirrorsHeated", "CruiseControl", "InfoCenter", "AutomaticClimateControl", "TripComputer", "Navigation", "GearShiftStearingWheel", "ServiceOK", "Immobilizer", "SeatHeater", "XenonLight" ]
My code so far i very simple as I struggle to list the data to a list i.e. LI or a TABLE :
<?php
$url = 'https://gw.bilinfo.net/listingapi/api/export';
// provide your username and password here
$auth = base64_encode("demo:ocfB6XzF73");
// create HTTP context with basic auth
$context = stream_context_create([
'http' => ['header' => "Authorization: Basic $auth"]
]);
// query for data
$data = file_get_contents($url, false, $context);
// $escaped = json_encode($data);
$escaped = json_decode($data); //, JSON_FORCE_OBJECT
/*Initializing temp variable to design table dynamically*/
$temp = "<table>";
/*Defining table Column headers depending upon JSON records*/
$temp .= "<tr>";
$temp .= "<th>Bil</th>";
$temp .= "<th>Model</th>";
$temp .= "<th>Motor</th>";
$temp .= "<th>Drivmiddel</th>";
$temp .= "<th>Udstyr</th>";
$temp .= "<th>Billeder</th>";
$temp .= "</tr>";
/*Dynamically generating rows & columns*/
foreach ($escaped->Vehicles as $vehicle) {
$temp .= "<tr>";
$temp .= "<td>" . $vehicle->Make . "</td>";
$temp .= "<td>" . $vehicle->Model . "</td>";
$temp .= "<td>" . $vehicle->Motor . "</td>";
$temp .= "<td>" . $vehicle->Propellant . "</td>";
foreach($escaped->Vehicles[0]->EquipmentList as $EquipmentItem){
$temp .= "<td>" . $EquipmentItem . "</td>";
}
for ($p = 0; $p < $vehicle->PictureCount; $p++) {
$temp .= "<td><img src='" . $vehicle->Pictures[0] . "'></td>";
}
}
$temp .= "</tr>";
/*End tag of table*/
$temp .= "</table>";
/*Printing temp variable which holds table*/
echo $temp;
echo $data;
?>
With the help of Anand Pandey
<?php
$url = 'https://gw.bilinfo.net/listingapi/api/export';
// provide your username and password here
$auth = base64_encode("demo:ocfB6XzF73");
// create HTTP context with basic auth
$context = stream_context_create([
'http' => ['header' => "Authorization: Basic $auth"]
]);
// query for data
$data = file_get_contents($url, false, $context);
// $escaped = json_encode($data);
$escaped = json_decode($data); //, JSON_FORCE_OBJECT
/*Initializing temp variable to design table dynamically*/
$temp = "<table class='car-list'>";
/*Defining table Column headers depending upon JSON records*/
$temp .= "<tr>";
$temp .= "<th class='th-style'>Bil</th>";
$temp .= "<th class='th-style'>Model</th>";
$temp .= "<th class='th-style'>Motor</th>";
$temp .= "<th class='th-style'>Drivmiddel</th>";
$temp .= "<th class='th-style'>Udstyr</th>";
$temp .= "<th class='th-style'>Billeder</th>";
$temp .= "</tr>";
/*Dynamically generating rows & columns*/
foreach ($escaped->Vehicles as $vehicle) {
$temp .= "<tr>";
$temp .= "<td class='td-style'>" . $vehicle->Make . "</td>";
$temp .= "<td class='td-style'>" . $vehicle->Model . "</td>";
$temp .= "<td class='td-style'>" . $vehicle->Motor . "</td>";
$temp .= "<td class='td-style'>" . $vehicle->Propellant . "</td>";
$temp .= "<td class='td-style'>";
foreach ($escaped->Vehicles[0]->EquipmentList as $EquipmentItem) {
$temp .= "<table>";
$temp .= "<tr>";
$temp .= "<td class='equipmentlist'>" . $EquipmentItem . "</td>";
$temp .= "</tr>";
$temp .= "</table>";
}
$temp .= "</td>";
$temp .= "<td class='td-style'>";
for ($p = 0; $p < $vehicle->PictureCount; $p++) {
$temp .= "<table>";
$temp .= "<tr>";
$temp .= "<td class='td-style'>";
$temp .= "<img class='cc-images' src='" . $vehicle->Pictures[$p] . "'>";
$temp .= "</td>";
$temp .= "</tr>";
$temp .= "</table>";
}
$temp .= "</td>";
}
$temp .= "</tr>";
/*End tag of table*/
$temp .= "</table>";
/*Printing temp variable which holds table*/
echo $temp;
//echo $data;
?>
Related
I am trying to get the EquipmentList from the Vehicles list in the JSON URL: JSON link
Look at documentation here: Link to documentation
I am trying to add the EquipmentList so that it appears in the table like the images... Just for now at least...
My code so far:
<?php
$url = 'https://gw.bilinfo.net/listingapi/api/export';
// provide your username and password here
$auth = base64_encode("demo:ocfB6XzF73");
// create HTTP context with basic auth
$context = stream_context_create([
'http' => ['header' => "Authorization: Basic $auth"]
]);
// query for data
$data = file_get_contents($url, false, $context);
// $escaped = json_encode($data);
$escaped = json_decode($data); //, JSON_FORCE_OBJECT
/*Initializing temp variable to design table dynamically*/
$temp = "<table>";
/*Defining table Column headers depending upon JSON records*/
$temp .= "<tr>";
$temp .= "<th>Bil</th>";
$temp .= "<th>Model</th>";
$temp .= "<th>Motor</th>";
$temp .= "<th>Drivmiddel</th>";
$temp .= "<th>Udstyr</th>";
$temp .= "<th>Billeder</th>";
$temp .= "</tr>";
/*Dynamically generating rows & columns*/
foreach ($escaped->Vehicles as $vehicle) {
$temp .= "<tr>";
$temp .= "<td>" . $vehicle->Make . "</td>";
$temp .= "<td>" . $vehicle->Model . "</td>";
$temp .= "<td>" . $vehicle->Motor . "</td>";
$temp .= "<td>" . $vehicle->Propellant . "</td>";
for ($e = 0; $e < $vehicle->EquipmentList; $e++) {
$temp .= "<td>" . $vehicle->EquipmentList[0] . "</td>";
}
for ($p = 0; $p < $vehicle->PictureCount; $p++) {
$temp .= "<td><img src='" . $vehicle->Pictures[0] . "'></td>";
}
}
$temp .= "</tr>";
/*End tag of table*/
$temp .= "</table>";
/*Printing temp variable which holds table*/
echo $temp;
//echo $data;
?>
"EquipmentList": [ "ABSBrakes", "Alarm", "AlloyRims", "AntiSpin", "AutomaticGear", "RemoteCentralLocking", "PoweredWindows", "PoweredMirrorsHeated", "CruiseControl", "InfoCenter", "AutomaticClimateControl", "TripComputer", "Navigation", "GearShiftStearingWheel", "ServiceOK", "Immobilizer", "SeatHeater", "XenonLight" ]
does $EquipmentList correctly describe the values inside the variable?
Perhaps $EquipmentItem is more correct?
if so, it will return an object (json)
for example
{
"name": "Motor 1 A",
"img": "/someimg.jpg"
}
to display an image, you need <img/> tag
foreach($escaped->Vehicles[0]->EquipmentList as $EquipmentItem){
$temp .= "<td>" . "<img src='" . $EquipmentItem->img . "' />" . "</td>";
}
Based on your example, the correct solution may vary, but this should give you idea if the correct question has been answered.
I modified Phillip Zoghbi's code - removed the image part c;) - So in part Phillip is right!
foreach($escaped->Vehicles[0]->EquipmentList as $EquipmentItem){
$temp .= "<td>" . $EquipmentItem . "</td>";
}
I am trying to get this JSON-data from here: https://gw.bilinfo.net/listingapi/api/export
They have a 'how to sheet' here: https://developer.bilinfo.net/content/Bilinfo_XML_API.pdf
I can connect with Authorization and can get the raw JSON, but I can't make a table with the data.
This is my code so far:
<?php
$url = 'https://gw.bilinfo.net/listingapi/api/export';
// provide your username and password here
$auth = base64_encode("demo:ocfB6XzF73");
// create HTTP context with basic auth
$context = stream_context_create([
'http' => ['header' => "Authorization: Basic $auth"]
]);
// query for data
$data = file_get_contents($url, false, $context);
$escaped = json_encode($data);
/*Initializing temp variable to design table dynamically*/
$temp = "<table>";
/*Defining table Column headers depending upon JSON records*/
$temp .= "<tr><th>Bilmodel</th>";
$temp .= "<th>Motor</th>";
$temp .= "<th>Drivmiddel</th></tr>";
/*Dynamically generating rows & columns*/
for ($i = 0; $i < sizeof($escaped["Vehicles"]); $i++) {
$temp .= "<tr>";
$temp .= "<td>" . $escaped["Vehicles"][$i]["Model"] . "</td>";
$temp .= "<td>" . $escaped["Vehicles"][$i]["Motor"] . "</td>";
$temp .= "<td>" . $escaped["Vehicles"][$i]["Propellant"] . "</td>";
$temp .= "</tr>";
}
/*End tag of table*/
$temp .= "</table>";
/*Printing temp variable which holds table*/
echo $temp;
?>
Solution 1.
JSON_FORCE_OBJECT on encoding PHP array value, then each array element will be added to an index even though if input array doesn’t have any index.
So you can just use
$escaped = json_encode($data, JSON_FORCE_OBJECT);
and your code will print the table.
Solution 2.
Currently json_encode converting data to StdObject in which you can read data using an arrow symbol. So printing data in your table just use foreach function reading Vehicles object with the arrow symbol.
/*Dynamically generating rows & columns*/
foreach ($escaped->Vehicles as $vehicle){
$temp .= "<tr>";
$temp .= "<td>" . $vehicle->Model . "</td>";
$temp .= "<td>" . $vehicle->Motor . "</td>";
$temp .= "<td>" . $vehicle->Propellant . "</td>";
$temp .= "</tr>";
}
I'm trying to access the "Climate" key. I can access all items outside of the "UnitFeatures" operator.
"Location": {
"Units": [
{
"BonusComments": "THIS IS A BONUS DEAL",
"CubicFootage": 125,
"OrderGrouping": "0000001CONTAINER",
"SquareFootage": 25,
"TotalUnits": 45,
"UnitFeature": {
"Access": "",
"Climate": "NON-CLIMATE",
"Doors": "",
"Elevation": "OUTSIDE",
"Floor": "1",
"Product": "CONTAINER"
},
},
]
}
I have been able to access using associative arrays. I also have a for loop that will output the information into a table.
$temp = "<table cellpadding='5px'>";
$temp .= "<tr><th>Unit Size</th>";
$temp .= "<th>Comments</th>";
$temp .= "<th>Unit Sq. Footage</th>";
$temp .= "<th>Units Available</th>";
$temp .= "<th>Monthly Rent</th></tr>";
for($i = 0; $i < sizeof($units) ; $i++) {
if($units[$i]["SquareFootage"]<=100) {
$temp .= "<tr>";
$temp .= "<td id='row'>" . $units[$i]["UnitSize"] . "</td>";
$temp .= "<td id='row'>" . $units[$i]["UnitFeature"]["Climate"] . "</td>";
$temp .= "<td id='row'>" . $units[$i]["SquareFootage"] . "</td>";
$temp .= "<td id='row'>" . $units[$i]["VacantUnits"] . "</td>";
$temp .= "<td id='row'>$" .$units[$i]['Monthly'] . ".00</td>";
$temp .= "</tr>";
}
}
$temp .= "</table>";
echo $temp;
I have tried the line that contains: $units[$i]["UnitFeature"]["Climate"] in every possible configuration.
The output should be either "Non-Climate" or "Climate".
After looking at the API documentation, it appears that the UnitFeature object is optional, and may be null. So the code needs to test for this:
foreach ($units as $u) {
if($u["SquareFootage"]<=100) {
$temp .= "<tr>";
$temp .= "<td id='row'>" . $u["UnitSize"] . "</td>";
if (isset($u["UnitFeature"]["Climate"])) {
$temp .= "<td id='row'>" . $u["UnitFeature"]["Climate"] . "</td>";
} else {
$temp .= "<td id='row'></td>";
}
$temp .= "<td id='row'>" . $u["SquareFootage"] . "</td>";
$temp .= "<td id='row'>" . $u["VacantUnits"] . "</td>";
$temp .= "<td id='row'>$" .$u['Monthly'] . ".00</td>";
$temp .= "</tr>";
}
}
I tried your json to decode with json_decode and it won't. Because it returns Syntax Error. You can check it with json_last_error_msg(). Also I removed some " , " from your json string. You can validate your json string at jsonlint. And now it's working.
<?php
$jsonString = '{"Location" : {
"Units" : [
{
"BonusComments": "THIS IS A BONUS DEAL",
"CubicFootage": 125,
"OrderGrouping": "0000001CONTAINER",
"SquareFootage": 25,
"TotalUnits": 45,
"UnitFeature": {
"Access": "",
"Climate": "NON-CLIMATE",
"Doors": "",
"Elevation": "OUTSIDE",
"Floor": "1",
"Product": "CONTAINER"
}
}
]
}}';
$jsonType = json_decode($jsonString);
foreach ($jsonType->Location->Units as $key => $value) {
echo "KEY : ". $key."<br/>";
echo $value->UnitFeature->Climate;
}
?>
I'm about month and a half into PHP. I tried to make function for fetching results from find_all_subjects():
function find_all_subjects() {
global $dbconnect;
$q = "SELECT * FROM subjects ORDER BY id ASC";
$subject_set = mysqli_query($dbconnect, $q);
confirm_query($subject_set);
return $subject_set;
}
and then making a new function which will loop the result in table rows. The problem is it loops just one result... when I did it with <ul> and <li> it worked fine but it doesn't seem to work when doing it with the table. My table core tags are in another document. So it's not that...
function navigacija() {
$s = find_all_subjects();
while($subjects = mysqli_fetch_assoc($s)) {
$out = "<tr>";
// Ime Teme
$out .= "<td width='25%' height='40'> <a href=\"admin_content.php?subject=" . urlencode($subjects['id']) . "\">";
$out .= $subjects['menu_name'];
$out .= "</a></td>";
// Vidljiva
if($subjects['visible'] == 1) {
$subjects['visible'] = 'DA';
} else {
$subjects['visible'] = 'NE';
}
$out .= "<td width='25%' height='40'><p align=\"center\">DA / NE";
$out .= "</p></td>";
// Broj Strana
$out .= "<td width='25%' height='40'>";
$pages_set = find_sub_from_pages($subjects['id']);
while($pages = mysqli_fetch_assoc($pages_set)) {
$out .= "" . $pages['menu_name'] . "";
$out .= "</td>";
}
// Vidljiva
$out .= "<td align=\"center\" width='25%' height='40'>";
$out .= "<img width=\"17px\" height=\"17px\" src=\"st/img/ic-arup.png\">
</img> <img width=\"17px\" height=\"17px\" src=\"st/img/ic-ardown.png\"></img> ";
$out .= "</td>";
$out .= "</tr>";
}
return $out;
}
the problem is that you reset
$out = "<tr>";
every time in the loop.
change this line to
$out .= "<tr>";
and only put declaration out of the loop
$out = "";
I have this block of text in an array:
"Stefan Olsson"
"Kungsvägen"
"Skolgatan"
xxxx-xx-xx
0735xxxxxx,
"Pär Davidsson"
"Skolgatan"
"Myntvägen"
xxxx-xx-xx
0709xxxxxx,
I parse this type of content to an CSV-file, for later usage in Excel. However, I want to fromat this text to fit in different columns in excell. So, when I open the CSV-file in Execel, I want the name to be in one column, the address in the column besides etcetc. How can I accomplish this? Should I use PHPExcel? Or could it be done with plain old PHP?
Here is my PHP-code
$gatunamn = $_POST['gata'];
$ort = $_POST['omrade'];
$csv_data = array();
$newSpider->fetchPage($gatunamn, $ort, $offset=0);
$obj = json_decode($newSpider->html);
echo "<div id='rightcontent'><table id='one-column-emphasis'>";
echo "<th><input type='checkbox' name='csv_all' id='csv_all'></th><th>Namn</th><th>Adress</th><th>Adress2</th><th>Adress3</th><th>Personnummer</th><th>Telefonnummer</th><th>Telefonnummer2</th>";
$antal_sidor = round($obj->search->wp->totalHits / $obj->search->wp->pageSize);
echo "<td></td>";
foreach($obj->search->wp->features as $fish) //Loopar ut 50st (pageSize)
{
echo "<tr>";
echo "<td><input type='checkbox' value='csv' class='csv'></td>";
echo "<td>" . $fish->name . "</td>";
$csv_data[] .= utf8_decode($fish->name);
foreach($fish->addresses as $ad)
{
echo "<td>" . $ad->label . " " . $ad->postcode . " " . $ad->area . "</td>";
$csv_data[] .= utf8_decode($ad->label . " " . $ad->postcode . " " . $ad->area);
}
if(!empty($fish->dateOfBirth))
{
$convert_date = substr($fish->dateOfBirth, 0, -3); //Gör om datum från timestamp
echo "<td>" . date("Y-m-d", $convert_date) . "</td>";
$convert_datee = date("Y-m-d", $convert_date);
$csv_data[] .= $convert_datee;
}
if(!empty($fish->phoneNumbers))
{
foreach($fish->phoneNumbers as $ph)
{
echo "<td>" . $ph . "</td>";
$csv_data[] .= $ph . ",";
}
}
echo "</tr>";
}
echo "</table>";
$j = 0;
for($i = 1; $i <= $antal_sidor; $i++)
{
echo "<a href='curl2.php?gatunamn=$gatunamn&ort=$ort&offset=$j'>" . $i . "</a> ";
$j += 100;
}
echo "</div>";
echo "<div id='debug'><pre>";
var_dump($csv_data);
echo "</pre></div>";
}
if(isset($_POST['export']))
{
$fp = fopen("eniroo.csv","w");
foreach(explode(",", implode("\n",$csv_data)) as $rad) {
fputcsv($fp, array(implode(',', str_getcsv($rad, "\n"))));
}
echo "<div id='csv_info'>";
echo "<a href='eniro.csv'>Hämta CSV-fil</a>";
echo "</div>";
}
// Restructure the original array into rows
$myDataArray = array_chunk($myDataArray, 5);
// Then write to CSV
$fp = fopen('file.csv', 'w');
foreach($myDataArray as $dataRow) {
fputcsv($fh, $dataRow);
}
fclose($fh)