extract a protion of html file [duplicate] - php

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

Related

how to access the value of blob column(image) in controller laravel

I make live search in laravel by ajax jquery
i send html code from controller to view but i can't display the value of blob column
function search (Request $request) {
if($request->ajax())
{ $output='';
$data=Club::all();
foreach($data as $record)
{
$output.='
<tr>
<td > '.$record->name.'</td>
<td > '.$record->country.'</td>
<td ><img src="data:image/png;charset=utf8;base64,{{base64_encode('.$record-
>logo.')}}" ></img></td> //this is uncorrect what is the correct syntax here???
</tr>
';
}
echo json_encode($output);
}
}
Try to return the data rather than display them using echo
json_encode() shall receive object or array, not HTML, return data from your API then format it in front-end.
if($request->ajax())
{ $output='';
$data=Club::all();
return json_encode($data); \\ return rather than display
}
if($request->ajax())
{
$output='';
$data=Club::all();
$path = $record->logo;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
foreach($data as $record)
{
$output.='
<tr>
<td > '.$record->name.'</td>
<td > '.$record->country.'</td>
<td ><img src="'.$base64.'" ></img></td> //this is uncorrect what is the correct syntax here???
</tr>
';
}
echo json_encode($output);
}

Return instead of echo in WP plugin

This is probably a stupid question, but I'm new to coding so here goes :-).
I'm trying to create a simple plugin for WordPress. The plugin gets data from a MySQL database and echos out a table with the results. My problem is when I use echo the plugin is places first on the page even if i put the shortcode in the middle of the page. I understand that is because I use echo instead of return. I just don't get how to use return in my case. Any help would be much appreciated :-).
Here's my code:
$get_runners = $connection->prepare('SELECT first_name, last_name, nick_name, FROM database WHERE status = :status ORDER BY first_name ASC');
$get_runners->execute([status=>'success']);
// Create the table
echo '
<table id="Table" class="start-list-table">
<thead>
<tr class="start-list-tr">
<th scope="col">Name</th>
<th scope="col">Club</th>
</tr>
</thead>
<tbody>
';
// Get the runner object:
$runners = $get_runners->fetchAll();
foreach($runners as $runner){
if($runner->nick_name)
{
$runner_name = $runner->first_name.' "'.$runner->nick_name.'" '.$runner->last_name;
}
else
{
$runner_name = $runner->first_name.' '.$runner->last_name;
}
echo '
<tr class="start-list-tr">
<td data-label="Name">'.$runner_name.'</td>
<td data-label="Club">'.$runner->club.'</td>
</tr>';
}
echo '</tbody>
</table>';
}
add_shortcode( 'startlist', 'create_startlist' );
You want to assign your output to a variable, instead of echoing:
$get_runners = $connection->prepare('SELECT first_name, last_name, nick_name, FROM database WHERE status = :status ORDER BY first_name ASC');
$get_runners->execute([status=>'success']);
// Create the table
$output = '
<table id="Table" class="start-list-table">
<thead>
<tr class="start-list-tr">
<th scope="col">Name</th>
<th scope="col">Club</th>
</tr>
</thead>
<tbody>
';
// Get the runner object:
$runners = $get_runners->fetchAll();
foreach($runners as $runner){
if($runner->nick_name)
{
$runner_name = $runner->first_name.' "'.$runner->nick_name.'" '.$runner->last_name;
}
else
{
$runner_name = $runner->first_name.' '.$runner->last_name;
}
$output .= '
<tr class="start-list-tr">
<td data-label="Name">'.$runner_name.'</td>
<td data-label="Club">'.$runner->club.'</td>
</tr>';
}
$output .= '</tbody>
</table>';
return $output;
}
add_shortcode( 'startlist', 'create_startlist' );
This uses concatenation to continue to fill the variable through your function. You then set the return to the $output variable.
Firstly read more about Shortcodes Output : https://codex.wordpress.org/Shortcode_API#Output
There are two ways that I can think of at this moment.
Using ob_start... basically you need to wrap you code in ob_start()
function create_startlist() {
ob_start();
/* CODE HERE */
return ob_get_clean();
}
Second is to use a concatenation operator
function create_startlist() {
$output = '';
$output .= 'OUTPUT HERE';
return $output;
}

laravel cannot display jsondata

I'm try to use jsondata to display the results.
This is my output.
Now i just try to display the result
public function resultsurvey($survey_id)
{
//$results=[];
$allResults= Results::where('survey_id', $survey_id)->get()->toArray();
$justResults=Results::select('results')->where('survey_id', $survey_id)->get();
$json = json_decode($justResults, true);
$aQuestions = array();
$aAnswers = array();
foreach($json as $sKey => $oItem) {
array_push($aQuestions, $sKey);
array_push($aAnswers, $oItem);
}
dd($aQuestions , $aAnswers);
}
in pure php i just use a but in the laravel it's not work.
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<?php foreach($aQuestions as $aQuestionsn){?>
<th scope="col"><?php echo $aQuestionsn; ?></th>
<?php }?>
</tr>
</thead>
<tbody>
<tr>
<?php foreach($aAnswers as $aAnswersn) {?>
<td><?php echo $aAnswersn;?></td>
<?php }?>
</tr>
</tbody>
</table>
</div>
How i can display the jsonstring ?
All i need look like this
well i think in your case there is another array inside your array you need to go inside that array
foreach($aAnswers as $aAnswersn)
{
foreach ($aAnswersn as $value)
{
echo $value;
}
}
At least your json_encode is possibly in the wrong location, try this:
public function resultsurvey($survey_id)
{
//$results=[];
$allResults= Results::where('survey_id', $survey_id)->get()->toArray();
$justResults=Results::select('results')->where('survey_id', $survey_id)->get();
$aQuestions = array();
$aAnswers = array();
// $justResults is a collection so loop through it
foreach($justResults as $sKey => $oItem) {
// $oItem is possibly JSON encoded at this stage
$oItem = json_decode($oItem, true);
array_push($aQuestions, $sKey);
array_push($aAnswers, $oItem);
}
dd($aQuestions , $aAnswers);
}
Please note all changes

Remove image from folder after deleting in codeigniter

I want to delete the image not only in database, but in folder too.
this is my model
public function delete($id)
{
if ($this->db->delete("np_gallery", "id = ".$id))
{
return true;
}
}
this is my controller
public function delete_image($id)
{
$this->np_gallery_model->delete($id);
$query = $this->db->get("np_gallery");
$data['records'] = $query->result();
$this->load->view('admin/gallery/gallery_listing',$data);
}
this is my view
<table class="table table-bordered">
<thead>
<tr>
<td>Sl No</td>
<td>Tag</td>
<td>Image</td>
<td>Action</td>
</tr>
</thead>
<?php
$SlNo=1;
foreach($records as $r)
{
?>
<tbody>
<tr>
<?php $image_path = base_url().'uploads';?>
<td><?php echo $SlNo++ ; ?></td>
<td><?php echo $r->tag; ?></td>
<td><img src="<?php echo $image_path; ?>/images/gallery/<?php echo $r->picture;?>" style=" width:35%; height:100px;"/></td>
<td>
</td>
</tr>
</tbody>
<?php } ?>
</table>
I succeed in deleting the data in the database, but the image in the folder are not also be deleted.
Add some extra code in your controller:
public function delete_image($id)
{
$image_path = base_url().'uploads/images/gallery/'; // your image path
// get db record from image to be deleted
$query_get_image = $this->db->get_where('np_gallery', array('id' => $id));
foreach ($query_get_image->result() as $record)
{
// delete file, if exists...
$filename = $image_path . $record->picture;
if (file_exists($filename))
{
unlink($filename);
}
// ...and continue with your code
$this->np_gallery_model->delete($id);
$query = $this->db->get("np_gallery");
$data['records'] = $query->result();
$this->load->view('admin/gallery/gallery_listing',$data);
}
}
Note: alternativelly, you can do it inside your model delete() method instead. Consider where it better fits your applicaction needs.
Try these
foreach ($query_get_image->result() as $record)
{
// delete file, if exists...
$filename = $image_path . $record->picture;
if (file_exists($filename))
{
unlink($filename);
}
// ...and continue with your code
$this->np_gallery_model->delete($id);
$query = $this->db->get("np_gallery");
$data['records'] = $query->result();
$this->load->view('admin/gallery/gallery_listing',$data);
}

php: simple_html_parse_DOM

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

Categories