php: simple_html_parse_DOM - php

I am using Laravel as framework and the class simple_html_parse_DOM to parse a website .
The problem is the foreach didn't work .It just parse the first element.
I want to parse the elements in every tr :
example of the page i want to parse:
<tr>
<td class="allf">ADWYA</td>
<td>8.85</td>
<td>9.02</td>
<td>8.84</td>
<td>3256</td>
<td>29369</td>
<td><b>9.02</b></td>
<td><span class="quote_up2">0.00%</span></td>
</tr>
<tr>
<td class="allf">AETECH</td>
<td>1.19</td>
<td>1.19</td>
<td>1.19</td>
<td>1193</td>
<td>1420</td>
<td><b>1.19</b></td>
<td><span class="quote_up2">0.00%</span></td>
</tr>
<tr>
<td class="allf">AIR LIQUIDE TUNISIE</td>
<td>147.00</td>
<td>147.00</td>
<td>147.00</td>
<td>6</td>
<td>882</td>
<td><b>147.00</b></td>
<td><span class="quote_up2">0.00%</span></td>
my code:
$html = new simple_html_dom();
$html->load_file('http://www.ilboursa.com/marches/aaz.aspx');
$e = $html->find('#tabQuotes',0)->find('.alri');
$i=0;
foreach ($e as $alri) :
$Nom = $alri->children($i)->children(0)->plaintext;
$Ouverture = $alri->children($i)->children(1)->plaintext;
$Haut=$alri->children($i)->children(2)->plaintext;
$Bas=$alri->children($i)->children(3)->plaintext;
$Volumetitre =$alri->children($i)->children(4)->plaintext;
$Volumedt=$alri->children($i)->children(5)->plaintext;
$Dernier =$alri->children($i)->children(6)->plaintext;
$Variation=$alri->children($i)->children(7)->plaintext;
$cours = \App\Cours::create(array(
'Nom'=>$Nom,
'Ouverture'=>$Ouverture,
'Haut'=>$Haut,
'Bas'=>$Bas,
'Volumetitre' =>$Volumetitre,
'Volumedt'=>$Volumedt,
'Dernier'=>$Dernier,
'Variation' =>$Variation
));
$i++;
endforeach;

$e = $html->find('#tabQuotes',0)->find('.alri');
// For every table
foreach ($e as $alri)
// For every tr
foreach($alri->find('tr') as $tr) {
// array of td
$tds = $tr->find('td');
$Nom = $tds[0]->plaintext;
$Ouverture = $tds[1]->plaintext;
$Haut = $tds[2]->plaintext;
$Bas = $tds[3]->plaintext;
$Volumetitre = $tds[4]->plaintext;
$Volumedt = $tds[5]->plaintext;
$Dernier = $tds[6]->plaintext;
$Variation = $tds[7]->plaintext;
$cours = \App\Cours::create(array(
'Nom'=>$Nom,
'Ouverture'=>$Ouverture,
'Haut'=>$Haut,
'Bas'=>$Bas,
'Volumetitre' =>$Volumetitre,
'Volumedt'=>$Volumedt,
'Dernier'=>$Dernier,
'Variation' =>$Variation
));
}

Related

Print PHP array into table views with foreach

I'm newbie in development and I have trouble with this below logic.
This is my sample DB.
$data = array(3) {
$x_count = 2;
[1] => $name = 'A';
$y_count = 2;
array(2) {
[1] => $name = 'A.1';
$z_count = 2;
array(2) {
[1] => $name = 'A.1.a';
$val = 1;
[2] => $name = 'A.1.b';
$val = 1;
}
[2] => $name = 'A.2';
$z_count = 2;
array(2) {
[1] => $name = 'A.2.a';
$val = 2;
[2] => $name = 'A.2.b';
$val = 2;
}
}
[2] => $name = 'B';
$y_count = 2;
array(2) {
[1] => $name = 'B.1';
$z_count = 2;
array(2) {
[1] => $name = 'B.1.a';
$val = 3;
[2] => $name = 'B.1.b';
$val = 3;
}
[2] => $name = 'A.2';
$z_count = 2;
array(2) {
[1] => $name = 'B.2.a';
$val = 4;
[2] => $name = 'B.2.b';
$val = 4;
}
}
}
And I have to print like this
I have no idea of using foreach loop to print data into this table or caculating the number of "colspan" for each of x, y, z title.
I really hope to receive some advice. Thanks a lot!
EDIT: the x_count, y_count and z_count are variables get from DB and it's not only 2.
EDIT2: my expected result looks like this:
<table>
<tr>
<th>x_name</th>
<td colspan = "7">A</td>
<td colspan = "7">B</td>
<th rowspan = "3">SUM</th>
</tr>
<tr>
<th>y_name</th>
<td colspan = "3">A.1</td>
<td colspan = "3">A.2</td>
<td rowspan = "2">SUM</td>
<td colspan = "3">B.1</td>
<td colspan = "3">B.2</td>
<td rowspan = "2">SUM</td>
</tr>
<tr>
<th>z_name</th>
<td>A.1.a</td>
<td>A.1.b</td>
<td>SUM</td>
<td>A.2.a</td>
<td>A.2.b</td>
<td>SUM</td>
<td>B.1.a</td>
<td>B.1.b</td>
<td>SUM</td>
<td>B.2.a</td>
<td>B.2.b</td>
<td>SUM</td>
</tr>
<tr>
<th>value</th>
<td>1</td>
<td>1</td>
<td>2</td>
<td>2</td>
<td>2</td>
<td>4</td>
<td>6</td>
<td>3</td>
<td>3</td>
<td>6</td>
<td>4</td>
<td>4</td>
<td>8</td>
<td>14</td>
<td>20</td>
</tr>
</table>
You don't need to add y_count, x_count, you can use count() function on the object $data instead.
Here is HTML's structure I created, you may take a look
For data easier to process, you can consider to use my data structure below
$data = [
[
"name" => 'A', // x_name
"children" => [
[
"name" => 'A.1', // y_name
"children" => [
[
"name" => 'A.1.a', // z_name
"value" => 1
],
]
]
]
],
...
];
NOTE: All the code's logic below is used for your provided HTML, not for my jsFiddle's HTML
First step: Run a loop on every element of array $data for processing x_name data. Assign each row's html to variable for further use
/* Init html variable for $x_name, $y_name, $z_name, $value */
$x_html = '';
$y_html = '';
$z_html = '';
$value_html = '';
foreach ($data as $x_index => $x_data) {
$x_children = $x_data['children'];
$x_colspan = 1; // this variable will be sum of 1 'SUM' column and each $y_colspan
foreach ($x_children as $y_index => $y_data) {
$y_children = $x_data['children'];
$y_colspan = count($y_children) + 1; // all of y's children column + SUM column
// Update x_colspan
$x_colspan += $y_colspan;
// process assign html to $y_html
$y_html .= '<td colspan = "'.$y_colspan.'">'.$y_data['name'].'</td>';
// add SUM column
if ($y_index == count($x_children)-1) {
$y_html .= '<td>SUM</td>';
}
$sum = 0;
foreach ($y_children as $z_index => $z_data) {
$z_value = $z_data['value'];
$z_html .= '<td>'.$z_data['name'].'</td>';
// add SUM column for every looped 2 $z_data column
if ($z_index == count($y_children)-1) {
$z_html .= '<td>SUM</td>';
}
$sum += $z_value; // sum all value of current y_children
$value_html .= '<td>'.$z_data['value'].'</td>';
}
// After finish assign z_html, value_html, sum it all
$value_html .= '<td>'.$sum.'</td>'
}
$x_html .= '<td colspan = "'.$x_colspan.'">'.$x_data['name'].'</td>';
}
Last step: you print out all variable x_html, y_html, z_html, value_html. Merge it with the actual table html
$table_html = '
<table>
<tr>
<th>x_name</th>
'.$x_html.'
<th rowspan = "3">SUM</th>
</tr>
<tr>
<th>y_name</th>
'.$y_html.'
</tr>
<tr>
<th>z_name</th>
'.$z_html.'
</tr>
<tr>
<th>z_name</th>
'.$value_html.'
</tr>
</table>
';
This code above may be not runable, it's just a idea. Hope it would help you

Create SQL query for Wordpress Multisite

I'm trying to create a SQL query for a Wordpress multisite. I just don't get an answer.
The multisite has an id of 2 and the table is also named 2. Can someone help my with it?
If I change wp_2_posts, wp_2_postmeta to wp_posts, wp_postmeta, then it will work but only for the multisite with id = 1. I try a lot but not correct result.
<table class="tg">
<tr>
<th colspan="4" class="tg-dqty"> <b>Vandaag: <?=$date?> <!–– automatic date ––> </b>
</th>
</tr>
<tr>
<td class="tg-apa9">Datum/Tijd</td>
<td class="tg-apa9">De klant</td>
<td class="tg-apa9">Kapper</td>
<td class="tg-apa9">Betaling</td>
</tr>
<?php
$query_res = "SELECT * FROM wp_2_posts as wp,wp_2_postmeta as wpm,wp_blogs as blg WHERE wp.ID=wpm.post_id and wpm.meta_key='_sln_booking_date' and wpm.meta_value='$date' and blg.blog_id='2'";
$results_d = $wpdb->get_results($query_res);
foreach($results_d as $resultsd)
{
$post_id = $resultsd->ID;
$first_name = get_post_meta($post_id, '_sln_booking_firstname', true);
$last_name = get_post_meta($post_id, '_sln_booking_lastname', true);
$date = get_post_meta($post_id, '_sln_booking_date', true);
$time = get_post_meta($post_id, '_sln_booking_time', true);
$services = get_post_meta($post_id, '_sln_booking_services', true);
$attendants = array();
foreach($services as $service)
{
$attendants[] = $service['attendant'];
}
$attendants = array_unique($attendants);
$attendant_names = '';
if(count($attendants) > 0)
{
$attendants = implode(',', $attendants);
$query_res = "SELECT post_title FROM `wp_2_posts`, `wp_blogs`
WHERE post_type='sln_attendant' AND ID IN ($attendants) AND blg.blog_id = '2'";
$results_a = $wpdb->get_results($query_res);
$disattendants = array();
foreach($results_a as $result)
{
$disattendants[] = $result->post_title;
}
$attendant_names = implode(',', $disattendants);
//print_r($results);
}
$status = $resultsd->post_status;
$statuses = array('sln-b-paid'=>'Betaald','sln-b-paylater'=>'Betaal later','sln-b-canceled'=>'Geannuleerd','sln-b-confirmed'=>'Bevestigd');
$classes = array('sln-b-paid'=>'tg-jsol','sln-b-paylater'=>'tg-8a9r','sln-b-canceled'=>'tg-jsolc','sln-b-confirmed'=>'tg-jsol');
?>
<tr>
<td class="<?=$classes[$status]?>">Om <?=$time?> uur<br><?=$date?></td>
<td class="<?=$classes[$status]?>"><?=$first_name?> <?=$last_name?></td>
<td class="<?=$classes[$status]?>"><?=$attendant_names?></td>
<td class="<?=$classes[$status]?>"><?=$statuses[$status]?></td>
</tr>
<?php
}
?>
</table>

extract a protion of html file [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 5 years ago.
I have used dompdf to create pdf file, I have used a portion of the html file ie between to generate pdf . (cut & pasted manual way)
since I have a valid pdf out put now, I want to further automate the process,
I want to copy all contents between tables
<table> </table>
to a file, would like to know what would be possible options in php.
any suggestion is highly appreciated
Don't use regex, instead use DomDocument.
The following class will extract out the content between any element. So load your html from your file, or just pass it the contents of ob_get_contents()
<?php
class DOMExtract extends DOMDocument
{
private $source;
private $dom;
public function __construct()
{
libxml_use_internal_errors(true);
$this->preserveWhiteSpace = false;
$this->strictErrorChecking = false;
$this->formatOutput = true;
}
public function setSource($source)
{
$this->source = $source;
return $this;
}
public function getInnerHTML($tag, $id=null, $nodeValue = false)
{
if (empty($this->source)) {
throw new Exception('Error: Missing $this->source, use setSource() first');
}
$this->loadHTML($this->source);
$tmp = $this->getElementsByTagName($tag);
$ret = null;
foreach ($tmp as $v) {
if ($id !== null) {
$attr = explode('=', $id);
if ($v->getAttribute($attr[0]) == $attr[1]) {
if ($nodeValue == true) {
$ret .= trim($v->nodeValue);
} else {
$ret .= $this->innerHTML($v);
}
}
} else {
if ($nodeValue == true) {
$ret .= trim($v->nodeValue);
} else{
$ret .= $this->innerHTML($v);
}
}
}
return $ret;
}
protected function innerHTML($dom)
{
$ret = "";
foreach ($dom->childNodes as $v) {
$tmp = new DOMDocument();
$tmp->appendChild($tmp->importNode($v, true));
$ret .= trim($tmp->saveHTML());
}
return $ret;
}
}
$html = '
<h3>HTML Table Example</h3>
<div>
<table id="customers">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
</div>';
$dom = new DOMExtract();
$dom->setSource($html);
echo '
<table cellspacing="0" cellpadding="3" border="0" width="100%">',
//match and return only tables inner content with id=customers
$dom->getInnerHTML('table', 'id=customers'),
//match all tables inner content
//$dom->getInnerHTML('table'),
'</table>';
https://3v4l.org/OkbQW
<table cellspacing="0" cellpadding="3" border="0" width="100%"><tr><th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr><tr><td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr><tr><td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr><tr><td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr><tr><td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr><tr><td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr><tr><td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr></table>
Try This
To Extract Data between tags try this code
Here $source will be your complete html code. And $match will be the data extracted between tags.
Code:
preg_match("'<table>(.*?)</table>'si", $source, $match);
if($match) echo "result=".$match[1];
Reference: Preg match text in php between html tags

How to insert html input to the returned table from the backend?

I want to append or insert a html input to the table's td. Do you know how?
This is my html form index.php:
<table class="stack">
<thead class="tblthead">
<tr>
<th>Filename</th>
<th width="400">Date/Time</th>
<th width="300">Action</th>
</tr>
</thead>
<tbody id="importable">
</tbody>
</table>
This is my backend.php, this is where i returned the data going to the frontend which is my index.php.
case 'filerec':
$arr =[
":userID" => $_SESSION['loggedIn_PH'][0]['user_id'],
];
$query = "SELECT * FROM file_rec_tbl WHERE user_id=:userID ORDER BY file_id DESC";
$stmt = $con -> prepare( $query );
$stmt -> execute( $arr );
$data = $stmt -> fetchAll();
$table = '';
for( $x = 0; $x < count($data); $x++ ) {
$table .= '<tr fileID="'.$data[$x]['file_id'].'">
<td>'.$data[$x]['file_name'].'</td>
<td>'.$data[$x]['file_datetime'].'</td>
<td>'.html('<input type="text"></input>')
</tr>';
}
exit ($table);
break;
I got an error to the last td. Can you please help me or suggest what might be a good solution to my problem.
Try may be your problem
$table = '';
for( $x = 0; $x < count($data); $x++ ) {
$table .= '<tr fileID="'.$data[$x]["file_id"].'">
<td>'.$data[$x]["file_name"].'</td>
<td>'.$data[$x]["file_datetime"].'</td>
<td><input type="text"></input></td>
</tr>';
}

My PHP File doesn't show up when i call a function

Code:
<?php
require 'Controllers/MenuController.php';
$menuController = new MenuController();
if(isset($_POST['types']))
{
$menuTables = $menuController->CreateTypeTables($_POST['types']);
}
else
{
$menuTables = $menuController->CreateTypeTables("%");
}
$title = 'Menus';
$content = $menuController->CreateMenuDropdownList(). $menuTables;
include 'Template.php';
?>
Basically when i do it this way, my page doesnt anything, not even a echo
It doesn't even show my background pic from css
But when i exclude the function:
<?php
require 'Controllers/MenuController.php';
$menuController = new MenuController();
// if(isset($_POST['types']))
//{
// $menuTables = $menuController->CreateTypeTables($_POST['types']);
// }
// else
// {
// $menuTables = $menuController->CreateTypeTables("%");
// }
$title = 'Menus';
$content = "test";
//$menuController->CreateMenuDropdownList() . $menuTables;
include 'Template.php';
?>
it shows my background pic and the content; 'test'.
I think there is something wrong with my functions but i triple checked them
Sooooo help!
Here is the MenuController.php file;
<?php
require ("Model/MenuModel.php");
class MenuController {
function CreateMenuDropdownList(){
$menuModel = new MenuModel();
$result = "<form action = '' method = 'post' width = 200px'>
Type:
<select name = 'types' >
<option value = '%' >All</option>
".$this->CreateOptionValues($menuModel->GetMenuTypes()).
"</select>
<input type = 'submit' value = 'Search' />
</form>";
return $result;
}
function CreateOptionValues(array $types){
$result = "";
foreach ($types as $type){
$result = $result . "<option value='$type'>$type</option>";
}
return $result;
}
function CreateTypeTables($types){
$menuModel = new MenuModel();
$menuArray = $menuModel->GetItemsByType($types);
$result = "";
foreach ($menuArray as $key => $product){
$result = $result .
"
<table class = 'coffeeTable'>
<tr>
<th></th>
<th>Name: </th>
<td>$product->desc</td>
<tr>
<tr>
<th></th>
<th>Type: </th>
<td>$product->type</td>
<tr>
<tr>
<th></th>
<th>Price: </th>
<td>$product->price</td>
<tr>
<form method='post'>
<button type='submit' name='insert' value='$product->id' class='button1'>Add</button>
</form>
</table>";
}
return $result;
}
}

Categories