This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 7 years ago.
I have a String and it gives a XML output , now I want to capture that value. But the problem is there are same variables and that needs to run in a loop.
It's a Shipping method activity tracking, means shiftment step by step process and outputing that
Here is the XML I am getting:
<ArrayOfConsignmentTrack xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<ConsignmentTrack>
<ERROR/>
<DOCKNO>AB000000002</DOCKNO>
<TRANSIT_LOCATION>ANDHERI BRANCH OFFICE, MUMBAI</TRANSIT_LOCATION>
<ACTIVITY>In Transit to</ACTIVITY>
<EVENTDATE>13 Apr 2015</EVENTDATE>
<EVENTTIME>18:27:40</EVENTTIME>
<NEXT_LOCATION>ANDHERI BRANCH OFFICE</NEXT_LOCATION>
<TRACKING_CODE>T</TRACKING_CODE>
</ConsignmentTrack>
<ConsignmentTrack>
<ERROR/>
<DOCKNO>AB000000002</DOCKNO>
<TRANSIT_LOCATION>OKHLA BRANCH, OKHLA</TRANSIT_LOCATION>
<ACTIVITY>Picked up and Booking processed</ACTIVITY>
<EVENTDATE>13 Apr 2015</EVENTDATE>
<EVENTTIME>17:27:53</EVENTTIME>
<NEXT_LOCATION/>
<TRACKING_CODE>T</TRACKING_CODE>
</ConsignmentTrack>
</ArrayOfConsignmentTrack>
Now I want a output like this:
I am using this code to get the value
$myXMLData = file_get_contents($URL);
$xml = (array)simplexml_load_string($myXMLData);
if($xml) {
$dataArray = (array)$xml['ConsignmentTrack'];
echo $DOCKNO = $dataArray['DOCKNO'];
echo $TRANSIT_LOCATION = $dataArray['TRANSIT_LOCATION'];
echo $ACTIVITY = $dataArray['ACTIVITY'];
echo $EVENTDATE = $dataArray['EVENTDATE'];
echo $EVENTTIME = $dataArray['EVENTTIME'];
echo $NEXT_LOCATION = $dataArray['NEXT_LOCATION'];
} else{
echo " - Invalid Docket No.";
}
But it's giving only one value. What loop structure do I have to use?
This should work for you:
Just load your string with simplexml_load_string(), then you can do: echo $xml->asXML(); to see the structure of the xml, to then see where you have to loop through.
<?php
$xml = simplexml_load_string($myXMLData);
echo "<table border='1'>";
echo "<tr>";
echo "<td>Transit Location</td>";
echo "<td>Activity</td>";
echo "<td>Event Date</td>";
echo "<td>Event Time</td>";
echo "<td>next Location</td>";
echo "</tr>";
foreach($xml->ConsignmentTrack as $v) {
echo "<tr>";
echo "<td>" . $v->TRANSIT_LOCATION . "</td>";
echo "<td>" . $v->ACTIVITY . "</td>";
echo "<td>" . $v->EVENTDATE . "</td>";
echo "<td>" . $v->EVENTTIME . "</td>";
echo "<td>" . $v->NEXT_LOCATION . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Related
From the research i conducted in SO, this is the only other question similar to what i need, but im afraid that i didnt help me (How to replace null results in sql query result table with a string?).
I have a table that prints the Medical History of a Patient, and the table cells are restored from a database.
A portion of the code is down below:
echo "<tr>";
echo "<th>MRI Onset Localisation</th>";
echo "<th>CNS MRI Lesions Y/N </th>";
echo "<th>CNS MRI Lesions No.</th>";
echo "<th>CNS MRI Location</th>";
echo "<th>Person Signing the form</th>";
echo "<th>Documented at</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['Onsetlocalisation'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['smoker'] . '<br>' . $row['cigars'] . '<br>' . $row['cigardate'] . "</td>";
echo "<td>" . $row['onsetsymptoms'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['MRIonsetlocalisation'] . "</td>";
echo "<td>" . $row['MRIenhancing'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['MRInum'] . "</td>";
echo "<td>" . $row['MRIenhancinglocation'] . "</td>";
echo "<td class='tdclass exempt'>" . $row['signer'] . "</td>";
echo "<td>" . $row['reg_date'] . "</td>";
echo "</tr>";
And the MySQL Query that returns those fields is
$sql = "SELECT * FROM tblName WHERE somefield = $somevar";
The thing is... Some of those fields are allowed to have NULL as a value, but for the front end of the app, i want the table cells that contain NULL values to print a standard string such as "N/A" or "Empty" but i need it to be done inside of the php table portion of my code, or so i think...
I found numerous questions about replacing NULL with a string inside of the MySQL query, but i don't care about that since the query doesn't appear at the end user outside of the table.
I tried to implement the coalescing operator in the following way, but no nothing was displayed:
echo "<td class='tdclass exempt'>" . $row['MRInum'] ?? "N/A" . "</td>";
Any help is absolutely welcome.
You need to put the expression in brackets to make it clear which parts are supposed to be evaluated by the null coalescing operator:
echo "<td class='tdclass exempt'>" . ($row['MRInum'] ?? "N/A") . "</td>";
If you don't, it thinks the "<td class='tdclass exempt'>" is part of the text to be checked for existence - which means it always returns true because that hard-coded text always exists.
You can do this in two ways.
From SQL:
COALESCE(fieldName, 'N/A') AS fieldName
will replace NULLs with, you guessed it, 'N/A'.
Otherwise, when you fetch the row,
$row = $stmt->fetch(PDO::FETCH_OBJECT);
you can vet it:
$replacements = [
'MRI_Data' => 'N/A',
'MRI_Type' => [
'001' => 'Single Scan',
'002' => 'Multi Scan',
'003' => 'Pulsed',
'(null)' => 'N/A',
],
];
foreach ($row as $key => $value) {
if (array_key_exists($key, $replacements)) {
if (is_array($replacement[$key])) {
if (empty($value)) {
$value = '(null)';
}
if (array_key_exists($value, $replacement[$key])) {
$row[$key] = $replacement[$key][$value];
}
} else {
if (empty($value)) {
$row[$key] = $replacement[$key];
}
}
}
}
This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
Read JSON Data Using PHP [duplicate]
(5 answers)
Closed 4 years ago.
I have a JSON file in this format I want to data display in the table using for loops and for each loop what can I do?
[{"fertilizer":
{"pg1":"-21.259515860749435","pg2":"24.741169305724725","lastyearlastmonth":"764.119","currentmonth":"601.671","currentyearytd":"5735.1","lastyearytd":"4597.6","pname":"Urea","mmonth":"11","period":"11","myear":"2017"}},{"fertilizer":{"pg1":"-20.53085432388131","pg2":"9.258986807905458","lastyearlastmonth":"631.435","currentmonth":"501.796","currentyearytd":"2227.9","lastyearytd":"2039.1","pname":"DAP","mmonth":"11","period":"11","myear":"2017"}},{"fertilizer":{"pg1":"67.37546062508531","pg2":"51.07126222636238","lastyearlastmonth":"36.635","currentmonth":"61.318","currentyearytd":"648.7","lastyearytd":"429.4","pname":"CAN","mmonth":"11","period":"11","myear":"2017"}}]
i want to display in table through loop but i have problem how can i display all data thrugh using loops
foreach ($data as $nt)
{
echo "<tr class='{$dispval} {$boldrow}' >";
echo "<td>{$nt[pname]}</td>";
echo "<td class='txtright'>" . number_format($nt[lastyearlastmonth],1) . " </td>";
echo "<td class='txtright'>" . number_format($nt[currentmonth],1) . " </td>";
echo "<td class='txtright'>" . number_format($nt[pg1],1) . " </td>";
echo "<td class='txtright'>" . number_format($nt[lastyearytd],1) . " </td>";
echo "<td class='txtright' >" . number_format($nt[currentyearytd],1) . " </td>";
echo "<td class='txtright'>" . number_format($nt[pg2],1) . " </td>";
echo "</tr>";
}
You are on the right way!
First of all, json is a plain string in PHP. You need to decode it first using: json_decode();
For example:
$items = json_decode('your json string here');
foreach($items as $item) {
echo "<tr>";
echo "<td>".$item->fertilizer->pg1."</td>";
echo "<td>".$item->fertilizer->pg2."</td>";
// etc
echo "</tr>";
}
I have been working on this for awhile and I am maybe making this more difficult than it is. Any shared knowledge would be very much appreciated.
My code calls data using an API, I was able to display it as a ordered list but I wanted to make it more presentable using a table format.
Ideally I the results to be displayed grouped by day.
Below is what I have created so far, but it is not outputting anything currently:
echo "<table>";
echo "<tr>";
echo "<th>Date</th>";
echo "<th>Number of Asteroids</th>";
echo "</tr>";
echo "<tr>";
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<td>" . $close_approach->close_approach_date . "</td>";
foreach ($data->near_earth_objects as $date => $count) {
echo"<td>" . sizeof($count) . "</td></tr>";
}
}
echo "<tr>";
echo "<th>Asteroid Name</th>";
echo "<th>Asteroid Size</th>";
echo "<th>Velocity</th>";
echo "<th>Passing Earth By</th>";
echo "</tr>";
echo "<tr>";
foreach ($data->near_earth_objects->$date as $near_earth_object) {
echo "<td>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</td>";
echo "<td>" . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . " metres</td>";
}
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<td>" . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "</td><td>". $close_approach->miss_distance->kilometers . " km</td></tr> ";
}
echo"</table>";
You should avoid echoing HTML code whenever possible. You can use PHP Short tags <?= and ?> to inject PHP into your HTML code. This line
echo "<td>" . $close_approach->close_approach_date . "</td>";
can then be changed to
<td><?=$close_approach->close_approach_date?></td>
Furthermore I don't see any PHP opening and closing tags (<?php and ?>) to start and end your PHP code (although this may just be lacking in your example)
You're only looping through your table data <td> tags not your table row <tr> tags. You have to include these in your loop to keep creating a new table rows for every item in your loop:
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<tr>";
Finally, PHP offers an alternative syntax for control structures. Check out the PHP documentation
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
You can use this to improve your existing code:
foreach ($data->near_earth_objects->$date as $near_earth_object) {
echo "<td>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</td>";
echo "<td>" . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . " metres</td>";
}
And turn it into something like this
foreach ($data->near_earth_objects->$date as $near_earth_object): ?>
<td><?=$near_earth_object->name?> <a href='<?=$near_earth_object->nasa_jpl_url?>'><?=$near_earth_object->nasa_jpl_url?></td>
<td><?=$near_earth_object->estimated_diameter->meters->estimated_diameter_min?> metres</td>
<? endforeach; ?>
I recommend creating the table as you'd like to see it just with HTML and then using PHP to dynamically populate it. What may help is, rather than having PHP echo all of the HTML, just use PHP to populate the data (i.e., separate data from display). Just as an example taken from here:
<?php foreach ($things as $thing): ?>
<li><?php echo $thing; ?></li>
<?php endforeach; ?>
To begin with I know very little PHP and no java/javascript or jquery. I have created an html table populated from mysql database. It is for a call log. I am wanting to click on either a <td> or <tr> to open the corresponding record in a new page to be viewed in more detail. I have thought about putting the call_id value in a hidden column to be used in a variable somehow, but don't know where to go from there or if that is anywhere near the correct way to accomplish this.
Assuming that you're creating the table doing something like this,
$results = some_mysql_query;
foreach ($results as $index => $array) {
echo "<tr>";
echo "<td>";
echo $array['RecordNumber'];
echo "</td>";
echo "<td>";
echo $array['CallerName'];
echo "</td>";
echo "<td>";
echo $array['Time'];
echo "</td>";
echo "<td>";
echo $array['Duration'];
echo "</td>";
echo "</tr>";
}
Then you can add in a link by doing something like this:
$results = some_mysql_query;
foreach ($results as $index => $array) {
echo "<tr>";
echo "<td>";
echo "<a href='recordInfo.php?record='" . $array['RecordNumber'] . "'>" . $array['RecordNumber'] . "</a>";
echo "</td>";
echo "<td>";
echo "$array['CallerName'];
echo "</td>";
echo "<td>";
echo $array['Time'];
echo "</td>";
echo "<td>";
echo $array['Duration'];
echo "</td>";
echo "</tr>";
}
NOTE the use of single-quotes, ', inside the double-quotes - and the '" / "' surrounding the variable.
Alternatively, your echo with the link could look like this:
echo "<a href='recordInfo.php?record='{$array['RecordNumber']}'>{$array['RecordNumber']}</a>";
These accomplish the same thing.
This principle is the same, BTW, if your code looks like this:
$results = some_mysql_query;
while ($row = mysql_fetch_array($result)) {
...
echo $row['RecordNumber'];
Also, in case you're not already aware of how this will work, your recordInfo.php will receive its information in the $_GET array; specifically, it will refer to the RecordNumber as $_GET['RecordNumber'].
I have this type of record in an HTML table:
<tr class="simplehighlight" onclick="window.location.href='./games/game191.php';">
<td>06/09/2007</td><td>Jennifer Woods Memorial Grand Prix</td><td>C54</td>
<td>Nikolayev, Igor</td><td>2431</td><td>Parry, Matt</td><td>2252</td><td class="text-center">1-0</td></tr>
I want to read in a delimited file, make an array, and populate the table: (sample record)
game191|06/09/2007|Jennifer Woods Memorial Grand Prix|C54|Nikolayev, Igor|2431|Parry, Matt|2252|1-0
I tried this, but it only displays the last record from the datafile (/games.csv)
<?php
// open delimited data file "|" if needed and read.
//game191|06/09/2007|Jennifer Woods Memorial Grand Prix|C54|Nikolayev, Igor|2431|Parry, Matt|2252|1-0
if(!isset($_SESSION['games_array'])) {$file = $_SERVER['DOCUMENT_ROOT'].'/games.csv';
$fp = fopen($file,"r"); $list = fread($fp, filesize($file));
$_SESSION['games_array'] = explode("\n",$list); fclose($fp);}
// extract variables from each tuple by iteration
foreach ($_SESSION['games_array'] as $v);{
$token = explode("|", $v);
//write the table row and table data
echo "<tr class=\"simplehighlight\" onclick=\"window.location.href='./games/";
echo $token[0]; echo ".php';\">";
echo "<td>";echo $token[1];echo "</td>"; echo "<td>";echo $token[2];echo "</td>";
echo "<td>";echo $token[3];echo "</td>"; echo "<td>";echo $token[4];echo "</td>";
echo "<td>";echo $token[5];echo "</td>"; echo "<td>";echo $token[6];echo "</td>";
echo "<td>";echo $token[7];echo "</td>";
echo "<td class=\"text-center\">"; echo $token[8];echo "</td>";
echo "</tr>";};
?>
What am I missing?
foreach ($_SESSION['games_array'] as $v);{
should be
foreach ($_SESSION['games_array'] as $v) {
Try with file():
$lines = file('filename');
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
do you have the right permissions to access that file? is your php error_reporting set to display all errors? you could try using only relative paths, have you tried that? try using file_get_contents...
It was simpler than I thought... I erred in reusing old junk code from another script.
I found this and it works!
<?php
$text = file('games.csv'); foreach($text as $line) {$token = explode("|", $line);
echo "<tr class=\"simplehighlight\" onclick=\"window.location.href='./games/";
echo $token[0]; echo ".php';\">";
echo "<td>";echo $token[1];echo "</td>"; echo "<td>";echo $token[2];echo "</td>";
echo "<td>";echo $token[3];echo "</td>"; echo "<td>";echo $token[4];echo "</td>";
echo "<td>";echo $token[5];echo "</td>"; echo "<td>";echo $token[6];echo "</td>";
echo "<td>";echo $token[7];echo "</td>";
echo "<td class=\"text-center\">"; echo $token[8]; echo "</td>";
echo "</tr>";};
?>
Let me know if you see any improvements or faster functions. Thank you !