why code not working althoug it looks okay to me? - php

I previously found a script while googling and used it for scrapping purpose, my main class
in my amazon.php, I wrote the following script
include('scrape.php');
set_time_limit(0);
$ASIN = 'B000GEM3RI';
$shipArray = shipingPrice($ASIN);
var_dump($shipArray);
print_r($shipArray);
echo $shipArray;
function shipingPrice($city){
$shipArray = array();
$scrape = new Scrape();
$url = 'http://www.amazon.com/gp/offer-listing/'.$city.'/ref=dp_olp_new?ie=UTF8&condition=new';
$scrape->fetch($url);
$data = $scrape->removeNewlines($scrape->result);
$data = $scrape->fetchBetween('<table cellspacing="0" cellpadding="0" width="100%" border="0"> <thead class="columnheader"><tr><th scope="col" class="price">Price + Shipping</th><th scope="col" class="condition">Condition</th><th scope="col" class="seller">Seller Information</th><th scope="col" class="readytobuy">Buying Options</th></tr></thead>','</table>',$data,true);
$rows = $scrape->fetchAllBetween('<tr','</tr>',$data,true);
$i=0;$j=0;
foreach ($rows as $row){
if($i!=0){
if($i!=2){
$record = array();
$cells = $scrape->fetchAllBetween('<td','</td>',$row,true);
$record['price'] = strip_tags($cells[0]);
if(stristr($record['price'],'oz')===False && stristr($record['price'],'/')===False)
{
$listPrice=$scrape->fetchBetween('$',' +',$record['price']);
}else{
$listPrice=$scrape->fetchBetween('$',' (',$record['price']);
}
//print_r($listPrice);
if($listPrice==''){
$listPrice=$scrape->fetchBetween('$',' &',$record['price']);
$shipPrice='0';
}else{
$shipPrice=$scrape->fetchBetween('+ $','s',$record['price']);
}
$shipPrice= floatval($shipPrice);
//####
$sellerIdInfo = $cells[2]; $sellerIdArray=$scrape->fetchAllBetween('&marketplaceSeller=0&seller=','"><b>',$sellerIdInfo);
if(count($sellerIdArray)>1){
$sellerId=$sellerIdArray[0];
}else{
$temp = explode('"id',$sellerIdArray[0]);
$sellerId=$temp[0];
}
//##
$sellerName =$scrape->fetchBetween('Seller:','Seller',$record['price']);
$sellerInfo=$scrape->fetchAllBetween('alt="','"',$cells[2],true);
$sellerName=str_replace(array('alt="','"'),array('',''),$sellerInfo[0]);
if($sellerName!=""){
//
}else{
$sellerName = $scrape->fetchBetween('<span class="sellerHeader">Seller:</span>','</b></a>',$cells[2],true);
$sellerName=str_replace("Seller:","",$sellerName);
$sellerName=$scrape->fetchBetween('<b>','</b>',$sellerName);
}
array_push($shipArray,array('sellerName'=>$sellerName,'sellerId'=>$sellerId,'price'=>$listPrice,'shipPrice'=>$shipPrice));
}
}
$i++;
}
return $shipArray;
}
the url for this scrip is amazon
when I echo it, var_dump it or print_r, an empty array is displayed, I checked the page using firebug and to me, looks like everything is okay in my code
can somebody tell me why I can access anything from the page although my code is okay?
thanks for helping me
EDIT:-
By adding return $this->result = curl_exec($ch); in my scrap class function fetch($url), I have assured that Page is being retrieved successfullly...
EDIT-2:-
after working on the advice as provided in answer, it tried
$shipArray[]=array('sellerName'=>$sellerName,'sellerId'=>$sellerId,'price'=>$listPrice,'shipPrice'=>$shipPrice);
in my function, but still the same empty array
EDIT-3
I changed the following function
function fetchBetween($needle1,$needle2,$haystack,$include=false){
$position = strpos($haystack,$needle1);
if ($position === false) { return ' it was null data'; }
when I echo echo $data; in my script file,
it was null data
is printed, so looks like this line of code $position = strpos($haystack,$needle1); is not working,
am I right?
if yes, what to do now?

Why are you defining a var as the result of a function that hasn't been defined yet?
$shipArray = shipingPrice($ASIN);
var_dump($shipArray);
print_r($shipArray);
echo $shipArray;
ShippingPrice function is lower in the code. IE shipArray will be empty

Gotcha, I was correct, issue was not with my code
on line
$data = $scrape->fetchBetween('<table cellspacing="0" cellpadding="0" width="100%" border="0"> <thead class="columnheader"><tr><th scope="col" class="price">Price + Shipping</th><th scope="col" class="condition">Condition</th><th scope="col" class="seller">Seller Information</th><th scope="col" class="readytobuy">Buying Options</th></tr></thead>','</table>',$data,true);
there was an extra space border="0"> <thead class, that was creating issue, once, I removed this the space from
<table cellspacing="0" cellpadding="0" width="100%" border="0"><thead class="columnheader">
my code became okay..
thanks to everyone

Related

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

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

PHP Warning: in_array() : Wrong datatype for second argument

NOTE: I realize this is old code, but I'm hoping to repair it to get by until we can move to a new system next year.
I'm getting these two recurring errors from the two lines of code below.
How do I fix these errors?
Errors:
PHP Warning: in_array() [function.in-array]: Wrong datatype for second argument line 120
PHP Fatal error: Call to a member function add_viewed() on a non-object line 121
Lines of code causing errors:
if (!in_array($HTTP_GET_VARS['products_id'], $items_ids_on_display)) {
$viewed->add_viewed($HTTP_GET_VARS['products_id']);
}
Full Code of file below
if (((tep_session_is_registered('customer_id')) or (ENABLE_PAGE_CACHE == 'false')) and (!$spider_flag)){
//*******************************************************************************
DEFINE('HIST_ROWS', 7); // number of rows per column on display
DEFINE('HIST_MAX_ROWS',7); // max number of products on display
DEFINE('HIST_MEM_TRIGGER', 1); // number when memory threshold kicks in
//*******************************************************************************
// register the array if not already done so
if (tep_session_is_registered('viewed') && is_object($viewed)) {
} else {
tep_session_register('viewed');
$viewed = new viewed_products;
$viewed->reset();
}
// empty the array if requested by the user
if (isset($HTTP_GET_VARS['action'])) {
if ($HTTP_GET_VARS['action'] == 'viewed_remove') {
$viewed->remove();
}
}
// start shift from line 106 to here
$items_ids_on_display = array();
// end shift
// display the box if we have history
if ($viewed->count_viewed() > 0) { // displaying
?>
<tr>
<td class="prodRowDivide">
<table border="0" width="100%" cellpadding="2" cellspacing="1">
<tr class="header">
<td>
<table border="0" width="100%" cellspacing="0" cellpadding="0">
<?php
echo '<tr><td nowrap valign="center" class="prodRowHead" height="22">Recently Viewed Products:<br></td></tr>
</table>
</td></tr>
<tr><td valign="top"><table border="0" cellpadding="3" align="left"><tr>';
$info_box_contents = array();
//$info_box_contents[] = array('text' => 'Recently Viewed');
//new infoBoxHeading($info_box_contents, false, false);
$row = 0;
$col = 0;
/* get the products array from the class containing all viewed products */
$items = $viewed->get_viewed_items();
$index = 1;
/* determine the first and last record we want to display*/
$first = sizeof($items)- HIST_MAX_ROWS;
$last = sizeof($items)-1;
if (($last+1) < HIST_MAX_ROWS) {$disp = ($last+1);} else {$disp = HIST_MAX_ROWS;}
if ($first < 0) {$first = 0;}
/* only fetch the info for products on display */
// $items_ids_on_display = array(); // shift to line 67
for ($i=$last, $n=$first; $i>=$n; $i--) {
$viewed_query = tep_db_query("select pd.products_name,
p.products_image_lrg
from " . TABLE_PRODUCTS . " p,
" . TABLE_PRODUCTS_DESCRIPTION . " pd
where p.products_id = '" . $items[$i] . "' and
pd.language_id = '" . $languages_id . "' and
pd.products_id = p.products_id");
if ($viewed_info = tep_db_fetch_array($viewed_query)) {
$items_on_display[$i] = array('id' => $items[$i],
'name' => $viewed_info['products_name'],
'image' => $viewed_info['products_image_lrg']);
$items_ids_on_display[]= $items[$i];
}
}
for ($i=$last, $n=$first; $i>=$n; $i--) {
$currentPage = (int)($HTTP_GET_VARS['products_id']);
if ($currentPage != $items[$i]) {
echo '<td align="left" class="smallText">'. tep_image_thumb(DIR_WS_IMAGES . $items_on_display[$i]['image'], $items_on_display[$i]['name'], '120', '120') . '</center></td>';
$row ++;
$index++;
}
}
?>
</tr></table></td></tr>
</table>
</td>
</tr>
<tr>
<td valign="top"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '5'); ?></td>
</tr>
<?php
}
// general condition
}
if (isset($HTTP_GET_VARS['products_id']) and ($HTTP_GET_VARS['action'] != 'viewed_remove')) {
if (!in_array($HTTP_GET_VARS['products_id'], $items_ids_on_display)) {
$viewed->add_viewed($HTTP_GET_VARS['products_id']);
}
} ?>
Thank you in advance for your help!
For the first error:
PHP Warning: in_array() [function.in-array]: Wrong datatype for second argument line 120
You are passing a value that is not an array into in_array. You can see from the docs that an array is explicitly required for the second argument. This is because if your first if-statement at the top of the code isn't valid, $items_ids_on_display is unset.
"How do I fix this error?"
Check for the existence of $item_ids_on_display before attempting to use it in in_array.
The line
$viewed->add_viewed($HTTP_GET_VARS['products_id']);
Is reportedly trying to use the value of $viewed as an object with a method of add_viewed(), where the value of $viewed is not actually an object (it is unset when the applicable if-statement isn't satisfied.)
"How do I fix this error?"
Like before, check for the existence of $viewed before trying to attempt to utilize it as an object.
Ignoring any other code review and focusing on the reported problems, your resulting code at the bottom should be:
if (isset($items_ids_on_display) && isset($viewed) && isset($HTTP_GET_VARS['products_id']) and ($HTTP_GET_VARS['action'] != 'viewed_remove')) {
if (!in_array($HTTP_GET_VARS['products_id'], $items_ids_on_display)) {
$viewed->add_viewed($HTTP_GET_VARS['products_id']);
}
}
Final Note
You should be programming with error_reporting(E_ALL) set so you see PHP notices along with the PHP warnings and errors. They will give you more insight as to why the warnings and errors are happening.

Multiple countdown timers using a PHP loop

What I'm trying to do is output data from my database using PHP. Alongside this data I'd like to include a countdown timer using the data from my database. Naturally, the timer is done using JavaScript but I'm struggling to work out how to include the PHP variable in the JavaScript code and then loop through all my results, including an instance of the timer on each row.
I'm testing over here: http://www.lineswritten.co.uk/Countdown/ - The red 'timer here' is where I'd want the top 4 instances of 'waiting...' to be. These four instances aren't included in my loop.
I presume this would be done with $count++ but I'm not sure how to code this all up.
My JavaScript timer has been grabbed from here: http://jsfiddle.net/HSx9U/
The code is the following:
JavaScript
var count1 = new countDown(new Date('2010/12/11 10:44:59'),'counter1', 'tomorrow 10:45')
,count2 = new countDown(new Date('2010/12/25'),'counter2', 'first christmas day 2010')
,count3 = setTimeout(function(){
return new countDown(new Date('2011/12/25'),'counter3', 'first christmas day 2011');
},2000)
,count4 = setTimeout(function(){
return new countDown(new Date('2100/01/01'),'counter4', 'a new era starts');
},4000);
function countDown(startTime, divid, the_event){
var tdiv = document.getElementById(divid)
,start = parseInt(startTime.getTime(),10)
,the_event = the_event || startTime.toLocaleString()
,to;
this.rewriteCounter = function(){
var now = new Date().getTime()
,diff = Math.round((start - now)/1000);
if (startTime > now)
{
tdiv.innerHTML = diff +' seconds untill ' + the_event;
}
else {clearInterval(to);}
};
this.rewriteCounter();
to = setInterval(this.rewriteCounter,1000);
}
HTML
<div id="counter1">waiting...</div>
<div id="counter2">waiting...</div>
<div id="counter3">waiting...</div>
<div id="counter4">waiting...</div>
HTML Table/PHP loop
<table>
<tr>
<th id="logo">Logo</th>
<th id="name">Name</th>
<th id="discount">Discount</th>
<th id="length">Sale Length</th>
<th id="time">Time Remaining</th>
<th id="what">On What</th>
<th id="small-print">Small Print</th>
<th id="link">Link to Sale</th>
</tr>
while ($row = mysql_fetch_array($result)) {
$discount = $row['discount'];
$product = $row['product'];
$terms = utf8_decode($row['terms']);
$brand_name = $row['brand_name'];
$code = $row['code'];
$link = $row['link'];
$logo = $row['logo'];
$length = $row['length'];
<tr>
<td headers="logo"><?php echo $logo;?></td>
<td headers="name"><p><?php echo $brand_name;?></p></td>
<td headers="discount"><p><?php echo $discount;?></p></td>
<td headers="length"><p><?php echo $length;?></p></td>
<td headers="time"><p style="color:#F00;">timer here</p></td>
<td headers="what"><p><?php echo $product;?></p></td>
<td headers="small-print"><p><?php echo $terms;?></p></td>
<td headers="link"><p>Redeem</p></td>
}
</table>
I presumed I could change the new Date('2010/12/11 10:44:59') to new Date('$newDate') but it didn't work.
Geting stuff from PHP to javascript is best done using PHP's json_encode() function. You can feed it an array like this:
$array = ('item1', 'item2');
echo '<script type="text/javascript">';
echo 'var myarray = '.json_encode($array).';';
// iterate etc here
echo '</script>';

Categories