Accessing Array within JSON Operator Array - php

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

Related

How to loop a JSON nested Array into table list

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

How to get loop JSON all of Array (from URL) into a HTML Table with php

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

How to parse this JSON url with Authorization to HTML table/ list with php

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

PHP read file match if statement

everyone I have the following file and I want to show lines that match on if condition and pass the other.
I have this TXT file:
Doc. number|Date|Price|Description|Name
100|11/11/2015|99|Test 1|Alex
101|11/11/2015|120|Test 2
102|11/11/2015|100|Test 3|John
102|11/11/2015|140||
103|11/11/2015|110|Test 4|
And this is my PHP code:
$file_handle = fopen("file.txt", "rb");
$i = 0;
echo "<table border='1'>";
echo "<tr><th>Doc. number</th><th>Date</th><th>Price</th><th>Description</th><th>Name</th></tr>";
while (!feof($file_handle)) {
$line_of_text = fgets($file_handle);
$parts = explode('|', $line_of_text);
if($i > 1) { // Pass the first line
echo "<tr>";
echo "<td>" . $parts[0] . "</td>"; // Doc. number
echo "<td>" . $parts[1] . "</td>"; // Date
echo "<td>" . $parts[2] . "</td>"; // Price
echo "<td>" . $parts[3] . "</td>"; // Description
echo "<td>" . $parts[4] . "</td>"; // Name
echo "</tr>";
}
$i++;
}
fclose($file_handle);
echo "</table>"
How I can check if there are no "Description" and/or "Name" in table and pass this line. I want to show(get) only line that match on if condition.
I will be very grateful if someone have idea. Thanks in advance.
As simple as
$file_handle = fopen("file.txt", "rb");
$i = 0;
echo "<table border='1'>";
echo "<tr><th>Doc. number</th><th>Date</th><th>Price</th><th>Description</th><th>Name</th></tr>";
while (!feof($file_handle)) {
$line_of_text = fgets($file_handle);
$parts = explode('|', $line_of_text);
if($i > 1 && !empty($parts[3]) && !empty($parts[4])) { // Pass the first line and lines without description / name
echo "<tr>";
echo "<td>" . $parts[0] . "</td>"; // Doc. number
echo "<td>" . $parts[1] . "</td>"; // Date
echo "<td>" . $parts[2] . "</td>"; // Price
echo "<td>" . $parts[3] . "</td>"; // Description
echo "<td>" . $parts[4] . "</td>"; // Name
echo "</tr>";
}
$i++;
}
fclose($file_handle);
echo "</table>"
Only print table row if we have name and description:
if($i > 1 && $parts[3] && $parts[4]) {
You can put condition before echo statement and if it will be false just skip "echo";
if (count($parts) === 5) {
$error = 0;
foreach ($parts as $part) {
if (empty($part)) error++;
}
if($i > 1 && $error === 0) {
echo "<tr>";
echo "<td>" . $parts[0] . "</td>"; // Doc. number
echo "<td>" . $parts[1] . "</td>"; // Date
echo "<td>" . $parts[2] . "</td>"; // Price
echo "<td>" . $parts[3] . "</td>"; // Description
echo "<td>" . $parts[4] . "</td>"; // Name
echo "</tr>";
}
}
I've a solution that can help you.
But why I think you need just scape the heading line. so I changed if($i > 1) to be if($i >0)
$file_handle = fopen("file.txt", "rb");
$i = 0;
echo "<table border='1'>";
echo "<tr><th>Doc. number</th><th>Date</th><th>Price</th><th>Description</th><th>Name</th></tr>";
while (!feof($file_handle)) {
$line_of_text = fgets($file_handle);
$parts = explode('|', $line_of_text);
if($i > 0) { // Pass the first line
if ( (!empty($parts[3])) && (!empty($parts[4])) ){
echo "<tr>";
echo "<td>" . $parts[0] . "</td>"; // Doc. number
echo "<td>" . $parts[1] . "</td>"; // Date
echo "<td>" . $parts[2] . "</td>"; // Price
echo "<td>" . $parts[3] . "</td>"; // Description
echo "<td>" . $parts[4] . "</td>"; // Name
echo "</tr>";
}
}
$i++;
}
fclose($file_handle);
echo "</table>"
Your file has a CSV structure, pipe delimited.
So parse it as a CSV.
Note the using of array_shift to get the header of the CSV and passing the delimiter parameter to fgetcsv.
Also consider using implode instead explicitly passing each member of the array between td tags.
Here's an example using two functions, one for parsing the CSV and returning the data,
and another one for displaying the data and doing the validation.
function getData($file){
$rows = array();
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, null, "|")) !== FALSE) {
$rows[] = $data;
}
fclose($handle);
}
return $rows;
}
function displayData($rows){
$header = array_shift($rows);
$output = '<table border="1">' . PHP_EOL;
$output .= '<tr><th>' . implode('</th><th>',$header) . '</th></tr>' . PHP_EOL;
foreach($rows as $row){
if (isset($row[3]) and isset($row[4]) and $row[3]!='' and $row[4]!=''){
$output .= '<tr><td>' . implode('</td><td>',$row) . '</td></tr>' . PHP_EOL;
}
}
$output .= '</table>';
return $output;
}
$rows = getData("pipe.txt");
print displayData($rows);
This will output the following
<table border="1">
<tr><th>Doc. number</th><th>Date</th><th>Price</th><th>Description</th><th>Name</th></tr>
<tr><td>100</td><td>11/11/2015</td><td>99</td><td>Test 1</td><td>Alex</td></tr>
<tr><td>102</td><td>11/11/2015</td><td>100</td><td>Test 3</td><td>John</td></tr>
</table>

Format text to fit in columns in Excel

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)

Categories