How to xml to php nested arrays? - php

I 'm a total PHP beginner and need some help :-)
Have this xml:
http://pastebin.com/ZSpNPhXH
And this scrypt:
<?php
// Retrieve XML File
$file = file_get_contents('livescore-feed.xml');
// Parse XML with SimpleXML
$livescore_data = new SimpleXMLElement($file);
foreach ($livescore_data->league as $league) {
echo "<table class='table table-striped table-bordered table-condensed'>";
echo "<thead><tr><th colspan='6' id='league'>" . $league->attributes()->name . "</th></tr></thead>";
echo "<tbody>";
foreach ($league->match as $match) {
$status = $match->attributes()->status;
$home = $match->home->attributes()->name;
$away = $match->away->attributes()->name;
$score = $match->home->attributes()->goals . " - " . $match->away->attributes()->goals;
// If match not yet started, there will be a ":" in 'status' attribute
if (strpos($match->attributes()->status,':') !== false) {
$score = "-";
}
echo "<tr><td class='status' id='match'>" . $status . "</td><td id='match' colspan='2'>" .
$home . "</td><td class='score' id='match'>" . $score . "</td><td id='match' colspan='2'>" .
$away . "</td>
</tr>";
}
echo "</tbody></table>";
}
?>
How to show/parse "events" also
Thank you very much for your help and suggestions

In the same way you parse other data!
foreach( $livescore_data->league as $league )
{
(...)
foreach( $league->match as $match )
{
(...)
# ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
foreach( $match->events->event as $event )
{
echo $event['assist'] . '<br>';
echo $event['player'] . '<br>';
(...)
}
}
}
You have to perform a loop through $match->events->event and you can get each <event> attribute using $event[attribute] syntax. So, $event['extra_min'], $event['minute'], etc...
You have only to adapt the code to your table structure.

Related

PHP For Loop jQuery UI Tabs

I am trying to display a list of Links in a table according to Distance and Category. I would like each distance to be a Tab and have the appropriate Links in each Tab. I am trying to accomplish this with A PHP Foreach loop and jQuery-UI Tabs.
Here is the code which gets the data and displays it in the table in each Tab.
The index function in the controller for the View and the function that gets the table data:
public function index() {
$data = array();
$db_name = $this->uri->segment(2);
$this->db->db_select($db_name);
$tables = $this->db->get('tableinfo');
$data['distances'] = array();
$data['tables'] = array(
'men' => array(),
'women' => array()
);
foreach($tables->result() as $row) {
if(!in_array($row->distance, $data['distances'])) {
array_push($data['distances'], $row->distance);
}
if(substr($row->displayname, 0, 4) == "Male") {
array_push($data["tables"]['men'], $row->displayname);
} else {
array_push($data["tables"]['women'], $row->displayname);
}
}
$data['dbname'] = $db_name;
$this->parser->parse('templates/header', $data);
$this->parser->parse('select/index', $data);
$this->parser->parse('templates/footer', $data);
}
public function gettable($table) {
$db_name = "championchipco_sowetomarathon2019";
$this->db->db_select($db_name);
redirect("results/index/" . $db_name . "/" . $table);
}
And the View:
<?php
$i = 1;
echo "<div class='row'>";
echo "<div class='col' id='tabs'>";
echo "<ul>";
foreach($distances as $distance) {
echo "<li><a href='#tabs-" . $i . "'>" . $distance . "</a></li>";
}
echo "</ul>";
foreach($distances as $distance) {
echo "<div id='tabs-" . $i . "'>";
echo "<table class='table' cellspacing='10' cellpadding='10'>";
echo "<tr><th style='font-size: 20px;'>Men</th><th style='font-size: 20px;'>Women</th><th style='font-size: 20px;'></tr>";
foreach($tables['men'] as $table) {
if(substr($table, -4) == $distance) {
echo "<tr>";
echo '<td>' . $tables['men'][$i] . '</td>';
echo '<td>' . $tables['women'][$i] . '</td>';
echo "</tr>";
}
}
echo "</table>";
echo "</div>";
$i++;
}
echo "</div>";
echo "</div>";
?>
At the moment, all of the data is being displayed in every Tab, instead of only display the Links for the particular category in a different tab. I can see that the 2nd table of Men and Women is slightly to the left of the top one so I think the loop is causing something to go wrong.
I have tried re-arranging the way the loops display the data in the View but cannot seem to get only the 10KM in the 10KM Tab, 21KM in 21KM Tab, etc.
Get the data of your second foreach by Ajax it will made your need simple
I mentioned to remove below foreach
foreach($distances as $distance) {
echo "<div id='tabs-" . $i . "'>";
echo "<table class='table' cellspacing='10' cellpadding='10'>";
echo "<tr><th style='font-size: 20px;'>Men</th><th style='font-size: 20px;'>Women</th><th style='font-size: 20px;'></tr>";
foreach($tables['men'] as $table) {
if(substr($table, -4) == $distance) {
echo "<tr>";
echo '<td>' . $tables['men'][$i] . '</td>';
echo '<td>' . $tables['women'][$i] . '</td>';
echo "</tr>";
}
}
echo "</table>";
echo "</div>";
$i++;
}

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>

php add random array not repeating most recent 5

I'm trying to re-write this code so that it goes with the columns that are going to be user-defined. With this, my challenge consists of
a) Needs to select random starting item from array
b) Select the next random color from the original array that is not equivalent to the most recent items selected based the number: $intNotesColumn + 1
I was thinking a do-while statement nested inside another was appropriate for this but am unsure how to go about this. Here is my code so far:
$metroUIcolors = array( "#A30061", "#8200CC", "008987", "#A05000", "#B85A93", "#C07807", "#E51400", "#297A29" );
$metroUIcolorsLength = count($metroUIcolors);
$intNotesColumn = 3; // This will be user-defined later
// Now I query the SQL database to get my base-code
if ($result->num_rows > 0) {
// output data of each row
echo '<table border=0 valign=top>'
. '<tr>'
. '<td colspan=' . $intNotesColumn . '>' . '<h1>header</h1>' . '</td>'
. '</tr>'
. '<tr>';
$counterRank = 1;
while($row = $result->fetch_assoc()) {
echo "<td bgcolor=" . $metroUIcolors[rand(0, $metroUIcolorsLength - 1)]. ">"
. "<h2>" . $row["username"] . '</h2><br />'
. "<p class='notes'>" . $row["notes"] . "</p>"
. "<p class='footnotes'>"
. "<br />Last Reset: " . $row["lastReset"]
. '<br />Last Update: ' . $row['lastUpdate']
. '<br />SessionID: ' . $row["sessionID"]
. "<br />Counter = " . $counterRank . "</td>". '</p>';
if ($counterRank % $intNotesColumn == 0)
{
echo '</tr><tr>';
}
$counterRank++;
}
echo '</tr></table>';
} else{
echo "No Notes Found in databases";
}
Then, why don't you do it order picking one color at a time. You could use shuffle() so that there will be a different starting color everytime.
<?php
$counterRank = 1;
// shuffle the array
shuffle($metroUIcolors);
while($row = $result->fetch_assoc()) {
$rand_color = $counterRank % $metroUIcolorsLength;
echo "<td bgcolor=" . $metroUIcolors[$rand_color]. ">";
// everything else
$counterRank++;
}
?>
If you insist on doing the way you said, you may create an array $colorCount which has color codes as keys and count as values.
<?php
$counterRank = 1;
$colorCount = array_fill_keys($metroUIcolors, 0);
while($row = $result->fetch_assoc()) {
do {
$rand_color = $metroUIcolors[rand(0, $metroUIcolorsLength - 1)];
} while ($colorCount[$rand_color] > 5);
echo "<td bgcolor=" . $rand_color. ">";
// everything else
$counterRank++;
$colorCount[$rand_color] += 1;
}
?>

Is it possible to dynamically build a table using PHP? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Is it possible to dynamically build a table using PHP?
I am using code such as the below to build tables etc. but as there are multiple I was wondering in this case is it possible for the table to be built dynamically based on the SQL query?
For example if I need to build another table then I can copy the below code and just edit the SQL rather than also editing the column headers etc. in the HTML.
Basically some method to simplify the below code so that it is more compact\tidier if being used multiple times on the same page.
Code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('core/connection.php');
if($conn){
$stid = oci_parse($conn, "
SELECT *
FROM
(
SELECT c1, c2, c3, c4
FROM t1
ORDER BY c1
)
WHERE ROWNUM <= 10
");
oci_execute($stid);
echo "<table class='table table-hover '>
<thread>
<tr>
<th>c1</th>
<th>c2</th>
<th>c3</th>
<th>c4</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo "<td>" . $row['0'] . "</td>";
echo "<td>" . $row['1'] . "</td>";
echo "<td>" . $row['2'] . "</td>";
echo "<td>" . $row['3'] . "</td>";
echo "</tr>";
unset($row);
}
echo "</tbody>
</table>";
oci_free_statement($stid);
oci_close($conn);
}
<?php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
First example on: http://www.php.net/manual/en/function.oci-execute.php
You could use something like jQuery DataTables, http://datatables.net/ - it will allow you build the table from a JSON-object that you have made with PHP (i.e. by using json_encode() on your SQL result).
Here's my 2 cents on it:
function DisplayRawDataset( $dataset, $connection) {
$res = !is_resource($dataset) ? mysqli_quert($dataset) : $dataset;
if ( !is_resource($res) ) return '';
$i = 0;
$retstr = "";
$retstr .= "<table" border=\"1\" style=\"border-collapse:collapse;\" cellspacing=\"0\" cellpadding=\"2\" >";
while($row = $res->fetch_assoc()){
if($i == 0){
reset($row);
$retstr .= "<tr>";
while(list($key, $val) = each($row)){
$retstr .= "<th><b>".htmlspecialchars($key)."</b></th>";
}
$retstr .= "</tr>";
}
$retstr .= "<tr>";
reset($row);
while(list($key, $val) = each($row)){
$retstr .= "<td>".htmlspecialchars($val)."</td>";
}
$retstr .= "</tr>";
$i++;
}
$retstr .= "</table>";
return $retstr;
}
U could probably do this
$return = "<table class='table table-hover '>
<thread>
<tr>";
foreach(oci_fetch_array($stid, OCI_NUM) as $key){
$return .= "
<th>".$key."</th>
";
}
$return .= "
</tr>
</thread>
<tbody>
<tr>";
foreach(oci_fetch_array($stid, OCI_NUM) as $key => $value) {
$return .= "<td>" . $value . "</td>";
}
$return .= "</tr>
</tbody>
</table>";
}
echo $return;
or something along this line...
I use this....
<?php
/**
#file: tableFunctions.php
#version: 1.0
*/
//Initialize $headersPrinted boolean
$headersPrinted = false;
function obj2Table($obj, $id, $loop)//Passed arguments should include the object, the id for the created table, and '1' for the default first loop
{
global $headersPrinted;
$print = false;
if ($loop == 1)
{
//Setup a table to output the object
echo "<table id=\"$id\" border='.5'>\r\n";
}
//Loop through the object
foreach ($obj as $name => $value)
{
//Check for nested objects
if (is_object($value))
{
//If it is a nested object, feed the child back through
obj2Table($value, $id, 0);
}//end if(is_object)
//Check for nested arrays
elseif (is_array($value))
{
//If it is a nested array, try to feed each array back through
foreach ($value as $arrayKey => $arrayValue)
{
obj2Table($arrayValue, $id, 0);
}
}//end elseif(is_array)
else
{
//Set the $print boolean to true to print the rows once the foreach ends
$print = true;
if (!$headersPrinted)
{
$keys[] = $name;
}
$cells[] = $value;
}//end else
}//end foreach
if ($print)
{
if (!$headersPrinted)
{
echo "<tr>\r\n";
foreach ($keys as $key)
{
echo "<th>$key</th>\r\n";
}
echo "</tr>\r\n";
$headersPrinted = true;
}
foreach ($cells as $cell)
{
echo "<td>$cell</td>\r\n";
}
echo "</tr>\r\n";
}
if ($loop == 1)
{
//Close the table
echo "</table>\r\n";
//Set the $headersPrinted boolean back to false
$headersPrinted = false;
}//end if(initialLoop)
}//end function obj2Table()
?>
The just include that file in your php. In your while statement for the query results, just add each row to an array like this.. $results[] = $row;. After the while loop, then send the results to the function like this... obj2Table($results, 'queryTable', 1);. NOTE: you would need to change your oci_fetch_array to oci_fetch_object.
You can do something like this...
$sql = "SELECT field1 as 'Colunm 1', field2 as 'Colunm 2', fieldn as 'Colunm n' FROM table;";
function buildTable($sql){
$tab = "";
$head = "";
$body = "";
if (is_string($sql) && $sql !== "") {
$qry = mysql_query($sql);
while ($fet = mysql_fetch_assoc($qry)) {
if ($head == "") {
$head = "<tr>";
foreach ($fet as $key => $val) {
$head .= "<th>{$key}</th>";
}
$head .= "<tr>";
}
$body .= "<tr>";
foreach ($fet as $key => $val) {
$body .= "<td>{$val}</td>";
}
$body .= "</tr>";
}
return "<table><thead>{$head}</thead><tbody>{$body}</tbody></table>";
}
}
echo buildTable($sql);
Yes , it is possible , but you are doing it wrong. HTML that you echo is not valid (some HTML elements have a required closing tag like <table></table> so you should output <table> and </table> in one echo). One of the options for you is to assign your dynamic HTML to a value and then echo the valid HTML.
$buffer = "<table class='table table-hover '>
<thread>
<tr>
<th>c1</th>
<th>c2</th>
<th>c3</th>
<th>c4</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
$buffer .= "<tr>
<td>" . $row['0'] . "</td>
<td>" . $row['1'] . "</td>
<td>" . $row['2'] . "</td>
<td>" . $row['3'] . "</td>
</tr>";
unset($row);
}
$buffer .= "</tbody>
</table>";
echo $buffer;

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