I want to put my outputted PHP into a table but it doesn't like it...
The layout I want is like this
ROW - Desctiption URL
ROW2- Meta Description
And it needs to keep this same layout even when I enter more then one URL.
What happens now is that when I input lots of urls it puts all of the same parts into the same cell.. How can I change this?
Sorry its hard to explain...
Here is the code:
<?php
ini_set( "display_errors", 0);
//make the array
$TAarray = explode("\n", strip_tags($_POST['TAData']));
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
echo '<tr>';
echo (isset($tags['description']))?"<tr><td>Description($line)</td> </tr>".$tags['description']:"<tr><td>Description($line)</td></tr><tr><td>No Meta Description</td></tr>.";
echo '</tr>';
}
?>
You've got some awkward HTML there.. Try doing it like this:
//start the table
echo "<table>";
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
//start a new row in the table
echo '<tr>';
if(isset($tags['description'])){
//add two cells to the table.
echo "<td>Description($line)</td>";
echo "<td>{$tags['description']}</td>";
} else {
echo "<td>Description($line)</td>"
echo "<td>No Meta Description</td>";
}
echo '</tr>';
}
echo "</table>";
//make the array
$data='http://stackoverflow.com
http://ebay.com/';
$TAarray = explode("\n", strip_tags($data));
echo "<table>";
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
echo '<tr>';
if(isset($tags['description'])){
echo "<tr><td>Description($line):".$tags['description']:" </td> "; else{
"</tr><tr><td>Description($line)</td></tr><tr><td>No Meta Description</td></tr>.";
echo '</tr>';
}
}
echo "</table>";
Related
I am newer to PHP and I am able to get the desired output but I am doing it one index position at a time. I am returning data from a .txt file and I need to insert this data into an HTML table I am creating using PHP. BUT FIRST I need to be able to get the same output without typing out every index position. I tried to use a forloop but it kept outputting only one line.
I manually outputted the lines from the file and it works. What loop in PHP would be best to achieve the same results and output these elements? IMPORTANT, as is I am able to sort and rsort (I want to be able to do this so if it can be implemented in the loop that would be awesome) any help is more than I have right now.
PHP
$books = array();
if ($fp)
{
while(true)
{
$lines_in_file = count(file($filename));
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
list($title, $author, $pubdate, $isbn) = explode('*', $line);
$new_line = explode('*', $line);
for($ii= 1; $ii <= $lines_in_file; $ii++){
$lines = fgets($fp); //Read each line
$member = trim($lines);
array_push($books, $member);
}
//This foreach only brings back the first like in the txt file, why?
$cntr = 0;
foreach($books as $element){
$cntr++;
$table .= "<tr>";
$table .= "<td>".$title."</td>";
$table .= "<td>".$author."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$isbn."</td>";
$table .= "</tr>\n"; //added newline
echo $element;
}
//sort($books);
// rsort($books);
echo $books[0];
echo "<br>";
echo $books[1];
echo "<br>";
echo $books[2];
echo "<br>";
echo $books[3];
echo "<br>";
echo $books[4];
echo "<br>";
echo $books[5];
echo "<br>";
echo $books[6];
echo "<br>";
echo $books[7];
echo "<br>";
echo $books[8];
echo "<br>";
echo $books[9];
echo "<br>";
echo $books[10];
echo "<br>";
echo $books[11];
echo "<br>";
echo $books[12];
echo "<br>";
echo $books[13];
echo "<br>";
echo $books[14];
echo "<br>";
echo $books[15];
echo "<br>";
echo $books[16];
echo "<br>";
echo $books[17];
}//END WHILE LOOP
fclose($fp ); //Close file
}
Having to make a few guesses here but i believe the file is going to look like:
title*author*pubdate*isbn
title*author*pubdate*isbn
title*author*pubdate*isb
if this is wrong, let me know
as long as the fie is not to large read it in to an array:
$book_array=file('book_file.txt');
//print_r($book_array); //is it an array of the books, one book per array key
now to separate each line:
foreach($book_array as $line){
$line_sep=explode('*',$line);
// with no sorting option you could just echo inside the loop
//if you want to keep sorting options we have to keep the separated lines
$new_book_array[]=$line_sep;
}
unset($book_array);//free up memory if needed
//print_r($new_book_array);//is it a multi-d array, book then the 4 elements
to sort our new multidimensoanl array:
usort($new_book_array, function($a, $b) {
return strcmp($a['0'], $b['0']);;
}); //this sorts on key 0 in your case title:
//print_r($new_book_array); // has it sorted properly
for display:
loop again
echo '<table><tr><th>Title</th><th>Author</th><th>Pub Date</th><th>ISBN</th></tr>';
foreach($new_book_array as $book){
//print_r($book); //is it each indervidual book array with 4 elements
echo '<tr><td>'.$book[0].'</td><td>'.$book[1].'</td><td>'.$book[2].'</td><td>'.$book[3].'</td></tr>';
}
echo '</table>';
I am trying to create an array from this data, but I donĀ“t get it. I tried with the array_merge function, but the array doesn't construct correctly. This is my code, I want to create an array with the different fields of the table.
<?php
require('extractorhtml/simple_html_dom.php');
$dom = new DOMDocument();
//load the html
$html = $dom->loadHTMLFile("http:");
//discard white space
$dom->preserveWhiteSpace = false;
//the table by its tag name
$tables = $dom->getElementsByTagName('table');
//get all rows from the table
$rows = $tables->item(0)->getElementsByTagName('tr');
echo '<input type="text" id="search" placeholder="find" />';
echo '<table id="example" class="table table-bordered table-striped display">';
echo '<thead>';
echo '<tr>';
echo '<th>Date</th>';
echo '<th>Hour</th>';
echo '<th>Competition</th>';
echo '<th>Event</th>';
echo '<th>Chanel</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
// loop over the table rows
foreach ($rows as $row)
{
// get each column by tag name
$cols = $row->getElementsByTagName('td');
// echo the values
echo '<tr>';
echo '<td>'.$cols->item(0)->nodeValue.'</td>';
echo '<td>'.$cols->item(1)->nodeValue.'</td>';
echo '<td>'.$cols->item(3)->nodeValue.'</td>';
echo '<td class="text-primary">'.$cols->item(4)->nodeValue.'</td>';
echo '<td>'.$cols->item(5)->nodeValue.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
You don't need to merge arrays, you just need to push onto a new array to create a 2-dimensional array.
$new_array = array();
foreach ($rows as $row)
{
// get each column by tag name
$cols = $row->getElementsByTagName('td');
// echo the values
echo '<tr>';
echo '<td>'.$cols->item(0)->nodeValue.'</td>';
echo '<td>'.$cols->item(1)->nodeValue.'</td>';
echo '<td>'.$cols->item(3)->nodeValue.'</td>';
echo '<td class="text-primary">'.$cols->item(4)->nodeValue.'</td>';
echo '<td>'.$cols->item(5)->nodeValue.'</td>';
echo '</tr>';
$new_array[] = array(
'date' => $cols->item(0)->nodeValue,
'hour' => $cols->item(1)->nodeValue,
'competition' => $cols->item(3)->nodeValue,
'channel' => $cols->item(5)->nodeValue
);
}
Based on your <th> values, you know which columns contain which values, so it looks like you'd just need to modify the code inside your foreach loop to append the values to an array rather than generating new HTML with them.
foreach ($rows as $row)
{
// get each column by tag name
$cols = $row->getElementsByTagName('td');
$array['date'] = $cols->item(0)->nodeValue;
$array['hour'] = $cols->item(1)->nodeValue;
$array['competition'] = $cols->item(3)->nodeValue;
$array['event'] = $cols->item(4)->nodeValue;
$array['chanel'] = $cols->item(5)->nodeValue;
$result[] = $array;
}
After this loop, $result will be an array of arrays containing the values from the <td>s, where each inner array represents one <tr>.
I have a table with data from sql. Some of the columns in the db have more than 1 name. I have created an array from them but now I need to compare the two while creating a table.
$strArrayChildren = explode(',', $children);
$strArrayChildren = str_replace('and', '', $strArrayChildren);
$childCount = count($strArrayChildren);
$strArrayGrades = explode(',',$the_grades);
$strArrayGrades = str_replace('(', '', $strArrayGrades);
$strArrayGrades = str_replace(')', '', $strArrayGrades);
$grades ='';
foreach($strArrayChildren as $child){
foreach($strArrayGrades as $grade){
if(strpos($grade, $child) !== false){
$grades = preg_replace('([a-z A-Z ()]+)', "", $grade);
}elseif(strpos($grade, $child) !== true){
$grades ='';
}
}
echo "<tr>";
echo "<td>{$child}</td>";
echo "<td>{$last_name}</td>";
echo "<td>Child</td>";
echo "<td>{$grades}</td>";
echo "</tr>";
}
When I run this code I get the grade of the student to match with the first name from the array, but then the rest of the grades keep trying to match with the first student even though there is a new row with a new name.
Any help would be great! Thank you!
I'm not sure about your database but this should work. I'm posting the response with static arrays.
<?php
$strArrayChildren = array("Becky"," Aaron"," Luke");
$the_grades = "9 (Susan), 5 (Luke)";
$strArrayGrades = explode(',',$the_grades);
echo "<html><body><table style='text-align: center; width: 400px;'>";
echo "<tr>";
echo "<td>Child</td>";
echo "<td>Grade</td>";
echo "</tr>";
foreach($strArrayChildren as $child){
$grades = "";
$child = trim($child);
foreach($strArrayGrades as $key => $grade){
if(strpos($grade, $child) > 0){
$grades = intval(preg_replace('/[^0-9]+/', '', $grade), 10);
}
}
echo "<tr>";
echo "<td>{$child}</td>";
echo "<td>{$grades}</td>";
echo "</tr>";
}
echo "</table></body></html>";
?>
Explanation:
you need to initialize $grades right after first loop start
There is no point to test both states of strpos() function
It's safe to check position of needle occurrence in the string (be grater than 0)
You need to change you regex for selecting numbers from an string.
Trim needle in strpos(); there are unwanted white space in some cases. Better to trim white spaces at the start of the loop
I have an array coming from a .csv file. These are coming from a real estate program. In the second column I have the words For Sale and in the third column the words For Rent that are indicated only on the rows that are concerned. Otherwise the cell is empty. I want to display a list rows only For Sale for example. Of course then if the user clicks on a link in one of the rows, the appropriate page will be displayed.
I can't seem to target the text in the column, and I can't permit that the words For Sale be used throughout the entire array because they could appear in another column (description for example).
I have tried this, but to no avail.
/* The array is $arrCSV */
foreach($arrCSV as $book) {
if($book[1] === For Sale) {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
I also tried this:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
Do you mean:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div></div>';
}else{
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
}
I found a solution here:
PHP: Taking Array (CSV) And Intelligently Returning Information
$searchCity = 'For Sale'; //or whatever you are looking for
$file = file_get_contents('annonces.csv');
$results = array();
$lines = explode("\n",$file);
//use any line delim as the 1st param,
//im deciding on \n but idk how your file is encoded
foreach($lines as $line){
//split the line
$col = explode(";",$line);
//and you know city is the 3rd element
if(trim($col[1]) == $searchCity){
$results[] = $col;
}
}
And then:
foreach($results as $Rockband)
{
echo "<tr>";
foreach($Rockband as $item)
{
echo "<td>$item</td>";
}
echo "</tr>";
}
As you can see I'm learning. It turns out that by formulating a question, a series of similar posts are displayed, which is much quicker and easier than using google. Thanks.
When echo'ed out instead of just removing all of the other meta tags it seems to be duplicating the description, for example:
BBC has 13 different meta tags, when I echo out just the description in my script it is duplicating it 13 times.
<?php
//make the array
$TAarray = explode("\n", strip_tags($_POST['TAData']));
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
echo '<tr>';
foreach ($tags as $meta)
{
echo (isset($tags['description']))?"<br><br />\nDescription($line):<br>\n".$tags['description']:"<br>\nDescription($line):<br>\nNo Meta Description.";
/*echo '<td>' . $meta . '</td>';*/
}
echo '</tr>';
}
?>
Here is the URL incase anyone wanted to see it working: http://php-playground.co.cc/testdir/metaex.php
PS
I know the checkboxes are not working they are only there for the layout
I think this is what you are trying to do:
<?php
//make the array
$TAarray = explode("\n", strip_tags($_POST['TAData']));
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
echo '<tr>';
echo (isset($tags['description']))?"<br><br />\nDescription($line):<br>\n".$tags['description']:"<br>\nDescription($line):<br>\nNo Meta Description.";
echo '<td>' . $tags['description'] . '</td>';
echo '</tr>';
}
?>
You'll note that have removed the second for loop.
You are looping over the meta tags, and for each meta tag you are echoing out the description.
Get rid of the loop.
If you use foreach with references, it's good practice to remove that reference after the loop:
foreach ($TAarray as $key => &$line)
{
$line = trim($line);
}
unset($line); # remove the reference for safety reasons
But as you don't iterate over $TAarray after that code, the code is superfluous anyway. Don't write superfluous code. I suggest the following:
//make the array
$TAarray = explode("\n", strip_tags($_POST['TAData']));
$TAarray = array_map('trim', $TAarray);
And I suggest you put that into a function of it's own:
/**
* #param string $html
* #return string[] lines
*/
function getTrimmedTextLinesArrayFromHTMLBlock($html)
{
$text = strip_tags($html);
$lines = explode("\n", $text);
$trimmed = array_map('trim', $lines);
return $trimmed;
}
You can then use it wherever you see fit. You can also test this function independently with different input:
$lines = getTrimmedTextLinesArrayFromHTMLBlock($_POST['TAData']));
$whitelist = array("description");
foreach ($lines as $line)
{
if (! $tags = get_meta_tags($line)) continue;
echo '<tr>';
foreach ($tags as $key => $meta)
{
if (! in_array($key, $whitelist)) continue;
echo '<td>' . $meta . '</td>';
}
echo '</tr>';
}
I hope this is helpful.