Crawling with PHP and XPATH - php

I'm crawling a page because I want to show it on our website. I have a problem with getting the link on each team though. I get the team name, but I cant get the href attribute.
My code looks like this:
elements = $xpath->query("//table/tr[contains(#class,'sr')]/td[contains(#class,'c')]");
$count = 0;
foreach ($elements as $elt) {
if($count == 0)
{
$stringInsert = utf8_decode($elt->textContent);
}
else if($count == 1)
{
// tries to echo the href here, but dont get it.
echo $elt->getAttribute('href')
$stringInsert .= ", '".trim(utf8_decode($elt->textContent))."'";
}
else if($count == 3)
{
$stringInsert .= ", ".utf8_decode($elt->textContent);
}
else if($count == 4)
{
$stringInsert .= ", ".utf8_decode($elt->textContent);
}
else if($count == 5)
{
$stringInsert .= ", ".utf8_decode($elt->textContent);
}
else if($count == 6)
{
$stringInsert .= ", ".utf8_decode($elt->textContent);
}
else if($count == 7)
{
$stringInsert .= ", ".utf8_decode($elt->textContent);
}
else if($count == 9)
{
$stringInsert .= ", ".utf8_decode($elt->textContent);
}
else if($count == 10)
{
$stringInsert .= ", ".utf8_decode($elt->textContent);
}
$count++;
if($count == 12)
{
echo $stringInsert;
$count = 0;
}
}
As you can see in the code, i try to echo the $elt->getAttribute('href') in count == 1, but it does not show anything.
I have tried to add a /a to the xpath conditions, but then it only gets the Team name and not all the other stuff like, score, point and etc.

You seem to query for the td Elements, which won't have an attribute href.
May this example is helpful:
//array to store the results
$res = array();
//loop over all <tr> elements of the table.srPoolPosition
foreach ($path->query("//table[contains(#class,'srPoolPosition')]/tr") as $row) {
//new array to store results in each row
$rowRes = array();
//get the <td> elements in current <tr>
$fields = $path->query('td', $row);
//skip if not 12 fields
if ($fields->length < 12) {
continue;
}
//loop over those
foreach ($fields as $field) {
//store the textcontent in the current rows array
$rowRes[] = utf8_decode($field->textContent);
}
//query for the link in the current row
$link = $path->query("a", $row)->item(0)->getAttribute('href');
//add the link to the results array
rowRes[] = $link;
//then add it to the results
$res[] = $rowRes;
}
//example loop over the results
foreach ($res as $tableRow) {
echo sprintf(
'%s: %s - %s<br>',
$tableRow[13], //link href
$tableRow[1], //name
$tableRow[7], //score 1
$tableRow[9] //score 2
);
}

Related

How to get a html-table from an sql-query with various numbers of columns?

I have a html-form to read out data from an SQL-database. The number of selections is completely free, which means that there are no obligatory fields.
I would like to show the results that meet all selected criteria in a html-table. Here is my code:
<?php
include("../files/zugriff.inc.php");
if (isset($_POST["submit"])) {
$sent = $_POST['sent'];
$datenWerte = array();
$fruitname = $_POST["fruitname"];
$fruitgroup = $_POST["fruitgroup"];
$vegetablegroup = $_POST["vegetablegroup"];
$country = $_POST["country"];
$season = $_POST["season"];
$diameter = $_POST["diameter"];
$color = $_POST["color"];
if(!empty($fruitgroup)) {
$datenWerte['fruitgroup'] = $fruitgroup;
}
if(!empty($vegetablegroup)) {
$datenWerte['vegetablegroup'] = $vegetablegroup;
}
if(!empty($country)) {
$datenWerte['country'] = $country;
}
if(!empty($season)) {
$datenWerte['season'] = $season;
}
if(!empty($diameter)) {
$datenWerte['diameter'] = $diameter;
}
if(!empty($color)) {
$datenWerte['color '] = $color;
}
foreach ($datenWerte as $key => $value) {
$spalten[] = $key;
$werte[] = "'$value'";
}
echo "<b>Results:</b><br><br>";
$sql = "SELECT * FROM fruitdatabase WHERE (" . implode(", ",
$spalten) . ") = (" . implode(", ", $werte) . ")";
$result = mysqli_query($db, $sql);
$data = array();
while($row = $result->fetch_object()){
$data[] = $row;
}
// Numeric array with data that will be displayed in HTML table
$aray = $data;
$nr_elm = count($aray); // gets number of elements in $aray
// Create the beginning of HTML table, and of the first row
$html_table = '<table border="1 cellspacing="0" cellpadding="2""><tr>';
$nr_col = count($spalten); // Sets the number of columns
// If the array has elements
if ($nr_elm > 0) {
// Traverse the array with FOR
for($i=0; $i<$nr_elm; $i++) {
$html_table .= '<td>' .$aray[$i]. '</td>'; // adds the value in
column in table
// If the number of columns is completed for a row (rest of
division of ($i + 1) to $nr_col is 0)
// Closes the current row, and begins another row
$col_to_add = ($i+1) % $nr_col;
if($col_to_add == 0) { $html_table .= '</tr><tr>'; }
}
// Adds empty column if the current row is not completed
if($col_to_add != 0) $html_table .= '<td colspan="'. ($nr_col -
$col_to_add). '"> </td>';
}
$html_table .= '</tr></table>'; // ends the last row, and the table
// Delete posible empty row (<tr></tr>) which cand be created after last
column
$html_table = str_replace('<tr></tr>', '', $html_table);
echo $html_table; // display the HTML table
}
mysqli_close($db);
?>
Unfortunately, it´s not working. Could somebody please help me to find the error?
Than you very much in advance!

Skip row if more than one cell is empty with PHP

I have a PHP script that generates an HTML table from a CSV file.
Right now if any cells are missing information, it skips the row. HOWEVER, I'd prefer if it skipped a row if more than one cell was missing. So if a row has 2 empty cells, it should skip.
I have marked it //edit here below but unsure how to acheive this.
<?php
$idsColumnsWanted = array(0,1,8,19);
echo "<table class='table table-bordered' id='example'>\n\n";
$f = fopen("users.csv", "r");
$first_line = false;
while (($line = fgetcsv($f)) !== false) {
// Restart column index
$i = 0;
$row ="";
if($first_line == false) {
$row = "<thead><tr>";
$col = "th";
} else {
$row = "<tr>";
$col= "td";
}
$is_empty = false;
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (! in_array($i, $idsColumnsWanted)) continue;
// edit here
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . " </".$col.">";
} else {
$is_empty = true;
}
// Increase index
$i++;
}
if($first_line == false)
$row .= "</tr></thead>";
else
$row .= "</tr>";
$first_line = true;
if ($is_empty) {
continue;
} else {
echo $row;
}
}
fclose($f);
echo "\n</table>";
?>
please try this code
$is_empty = false;
$count = 0;
$countlimit = 2; // define empty cell limit here
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (!in_array($i, $idsColumnsWanted))
continue;
// edit here
if($cell==""){
$count++;
}
if ($count <= $countlimit) {
$row .= "<" . $col . ">" . htmlspecialchars($cell) . " </" . $col . ">";
} else {
$is_empty = true;
break;
}
}
You have to cound how many cells are empty in a row. To do so init the counter for each line.
$empty_cells = 0; //Init with 0 for each line
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (! in_array($i, $idsColumnsWanted)) continue;
// edit here
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . " </".$col.">";
} else {
$empty_cells++; //count how many empty cells you have.
}
// Increase index
$i++;
}
and after that check if there are more than two empty cells like this:
if ($empty_cells >= 2) {
continue;
} else {
echo $row;
}

Loop through mysqli results array once to get all information

I am querying the database for data, but in order to do what I need, I end up looping through that results array at least three times. How do I get all of the info I need out of the array without having to loop so many times? I need to get data from the array based on the results from the previous loops. The code below is the only way I could figure out in order to only query the database once.
$recordSQL = mysqli_query($link, $sqlString);
$resultMonths = array();
while($recordResult = mysqli_fetch_assoc($recordSQL)) $resultMonths[] = $recordResult['date'];
mysqli_data_seek($recordSQL, 0);
$uniqueMonths = array_unique($resultMonths);
foreach($uniqueMonths as $key => $date){
echo '</div><div class="current-month">'.translateDate($date, '').'</div>';
$resultCompanies = array();
while($companyResult = mysqli_fetch_assoc($recordSQL)){
if($companyResult['date'] == $date) $resultCompanies[] = $companyResult['company'];
}
mysqli_data_seek($recordSQL, 0);
$uniqueCompanies = array_unique($resultCompanies);
$oldco = '';
foreach($uniqueCompanies as $key => $company){
$x = 0;
while($typeResult = mysqli_fetch_assoc($recordSQL)){
if($typeResult['date'] == $date && $typeResult['company'] == $company){
if($oldco != $typeResult['company']){
if($x != 0) echo '</div>';
echo '<div class="company-record">'.$typeResult['name'].' - ';
}
if($x > 0) echo ', ';
echo translateID('Type', $typeResult['type']).'('.translateID('Section', $typeResult['section']).')';
$oldco = $typeResult['company'];
$x++;
}
}
echo '</div>';
mysqli_data_seek($recordSQL, 0);
}
}
FYI, you are actually looping N**3 times. Do it this way:
$month_company_rows = array();
while ($row = mysqli_fetch_assoc($recordSQL)) {
$month_company_rows[$row['date']][$row['company']][] = $row;
}
foreach ($month_company_rows as $date => $company_rows) {
echo '</div><div class="current-month">'.translateDate($date, '').'</div>';
foreach ($company_rows as $company => $rows) {
echo '<div class="company-record">'.$company.' - ';
foreach ($rows as $x => $row) {
if($x > 0) echo ', ';
echo translateID('Type', $row['type']).'('.translateID('Section', $row['section']).')';
}
echo '</div>';
}
}

How to show the value of two related arrays in php?

I have two arrays myarray1 has name of images and myarray2 has the address of images,
I am going to show image names and their addresses in pagination but do not know how to complete the code.
$pages = array_chunk($myarray1,10);
$addrs = array_chunk($myarray2,10);
$page_number = 1
$count = 0;
echo'<table>';
echo'<tr>';
foreach ($pages[$page_number] as $i) {
$counter++;
if ($count == 5) {
echo '</tr><tr>';
$counter = 0;
}
echo'<td>'.$i. " AND " . <<Value of addrs array goes here
echo'</td>';
}
.......
I'll do it on this way
$count = 1;
foreach ($pages[$page_number] as $key => $i) {
if ($count % 5 == 0) {
echo '</tr><tr>';
echo '</div>';
echo '</div>';
}
echo'<td>'.$i. " AND " . $addrs[$page_number][$key]
echo'</td>';
$count++; // increase at the end.
}
if you can try to var_dump those arrays before foreach just to be clear how structure looks like.
Try something like this: (note also the counter++ is changed in $count++)
foreach ($pages[$page_number] as $key => $i) {
$count++;
if ($count == 5) {
echo '</tr><tr>';
echo '</div>';
echo '</div>';
$count = 0;
}
echo'<td>'.$i. " AND " . $addrs[$page_number][$key]
echo'</td>';
}

php mysql_fetch_array every 25 items wrap a div

I want to mysql_fetch_array 100 items from mysql database. then every 25 items wrap a div.
also, I make a total items result check.
My code as below, but it will add <div> to every item, no as my require. So how to make it easier? Thanks.
if (mysql_num_rows($result) != 0) {
$total = mysql_num_rows($result);
$num = 1;
while ($row = mysql_fetch_array($result)) {
if ($num === 1) {
echo '<div>';
}
echo $row['title'] . '<br />';
if ($total < 26) {
echo '</div>';
}
else {
if ($num === 26) {
echo '<div>';
}
if ($total < 51) {
echo '</div>';
}
else {
if ($num === 51) {
echo '<div>';
}
if ($total < 76) {
echo '</div>';
}
else {
if ($num === 75) {
echo '<div>';
}
if ($total < 101) {
echo '</div>';
}
}
}
}
$num++;
}
}
You can use the mod operator.
See: http://php.net/manual/en/internals2.opcodes.mod.php
echo '<div>';
while($row = mysql_fetch_array($result)){
....
if (($num % 25) === 1) { echo '</div><div>' }
$num++;
}
echo '</div>';
Try This...
if(mysql_num_rows($result)!=0){
$total = mysql_num_rows($result);
$num=1;
while($row = mysql_fetch_array($result)){
if($num===1)
echo '<div>';
echo $row['title'].'<br />';
if($num==25){
echo '</div>';
$num=1;
}
$num++;
}
}
use the mod operator.
$num =1;
while($row = mysql_fetch_array($result)){
if (($num % 25) === 1) { echo '<div>' }
-------here data ----
if (($num % 25) === 0) { echo '</div>' }
$num++;
}
My advice is to separate your concerns... Give it a shot more like this:
// first get all your data.
$results = array();
while($row = mysql_fetch_array($result)){
$results[] = $row;
}
// now you have an array of all of your records.
if (!empty($results)) {
// total count of the array up front.
$total = count($results);
$interval = 0;
// save the data in a buffer for echoing later.
$buffer = array('<div>');
foreach($results as $row) {
$buffer[] = $row['title'] . '<br />';
if (++$interval === 24) { // notice the prefix ++
$interval = 0;
// close and re-open divs
$buffer[] = '</div><div>';
}
}
// one final close tag
$buffer[] = '</div>';
// now we zip it up and echo the content.
echo implode('', $buffer);
}
Here is how I do it...
$count = 0;
while($row = mysql_fetch_array($result)){
if ($count%$25 == 0)
{
echo "<div>";
}
//whatever your data goes here
count++
if ($count%$25 == 0)
{
echo "</div>";
}
}

Categories