Reverse read xml file in php - php

This is my php code
$xml=simplexml_load_file("data/listings.xml") or die("Error: Cannot create object");
foreach($xml->children() as $listings){
echo "<div class='col-md-4 top-text'>";
echo "<a href='?p=single&n=" . $listings->time . "'><img src='thumbnails/" . $listings->images . ".jpg' class='img-responsive' alt=''></a>";
echo "<h5 class='top'><a href='?p=single&n=" . $listings->time . "'>" . $listings->title . "</a></h5>";
echo "</div>";
}
I can not read from end to start using the below code.
foreach(array_reverse($xml->children()) as $listings){
echo "<div class='col-md-4 top-text'>";
echo "<a href='?p=single&n=" . $listings->time . "'><img src='thumbnails/" . $listings->images . ".jpg' class='img-responsive' alt=''></a>";
echo "<h5 class='top'><a href='?p=single&n=" . $listings->time . "'>" . $listings->title . "</a></h5>";
echo "</div>";
}

When you call children() on a SimpleXMLElement, you get another SimpleXMLElement back and not an array, so you can't call array_reverse() on it. A simple way round this is to use a for() loop instead...
for ( $i=$xml->children()->count()-1; $i>=0; $i-- ) {
$list = $xml->children()[$i];
echo "<div class='col-md-4 top-text'>";
echo "<a href='?p=single&n=" . $listings->time . "'><img src='thumbnails/" . $listings->images . ".jpg' class='img-responsive' alt=''></a>";
echo "<h5 class='top'><a href='?p=single&n=" . $listings->time . "'>" . $listings->title . "</a></h5>";
echo "</div>";
}
The reason why you can use it in a foreach() normally is that it implements Traversable, which allows you to process it using various methods as though it was an array.

Related

Ignoring data when using SimpleXML to list children

I'm using Simple XML to format election results data into a user-friendly webpage. I'm listing the races and candidates using PHP foreach, but there's some extra data (7 elements, to be exact) nested under each race that's being treated as candidates. How can I filter them out?
Here's the XML: https://ftpcontent.worldnow.com/wicu/BTI/election.xml
Here's the code output: https://lillydigitalmedia.com/election.php
Here's the code:
<?php
$btiresults = simplexml_load_file("https://ftpcontent.worldnow.com/wicu/BTI/election.xml");
echo "<p><em>Updated: " . $btiresults['Time'] . "</em></p>";
foreach($btiresults->children() as $race) {
echo "<h4 class='card-title' style='margin-top: 20px'><strong>" . $race->Name1 . "</strong></h4>";
foreach($race->children() as $candidate) {
echo "<p style='width: 100%;'><span style='float: left;'><strong>" . $candidate->Name . "</strong> <small>" . $candidate->Party . "</small></span><span style='float: right;'>" . $candidate->Votes . " votes</span></p>";
echo "<div class='progress' style='height: 25px; width: 100%;'>";
echo "<div class='progress-bar' role='progressbar' style='width:" . $candidate->PercentageOfVotesCast . "%' aria-valuenow='" . $candidate->PercentageOfVotesCast . "' aria-valuemin='0' aria-valuemax='100'>" . $candidate->PercentageOfVotesCast . "%</div>";
echo "</div>";
}
}
?>
Thanks in advance.
Since you are dealing with xml, you might as well use xpath.
Try something like the following (after the existing echo "<p><em>Updated: " . $btiresults['Time'] . "</em></p>";):
$races = $btiresults->xpath('//Race');
foreach($races as $race) {
echo "<h4 class='card-title' style='margin-top: 20px'><strong>" . $race->Name1 . "</strong></h4>";
foreach($race->xpath('./Candidate') as $candidate) {
echo "<p style='width: 100%;'><span style='float: left;'><strong>" . $candidate->Name . "</strong> <small>" . $candidate->Party . "</small></span><span style='float: right;'>" . $candidate->Votes . " votes</span></p>";
echo "<div class='progress' style='height: 25px; width: 100%;'>";
echo "<div class='progress-bar' role='progressbar' style='width:" . $candidate->PercentageOfVotesCast . "%' aria-valuenow='" . $candidate->PercentageOfVotesCast . "' aria-valuemin='0' aria-valuemax='100'>" . $candidate->PercentageOfVotesCast . "%</div>";
echo "</div>";
}
}
and see if it works.
You could simply look at the tag name of the Element, using SimpleXMLElement::getName.
Wrap the content of your inner foreach loop into an if condition that checks if it is Candidate:
foreach($race->children() as $candidate) {
if($candidate->getName() == 'Candidate') {
echo '…';
}
}
(Might perhaps make sense to rename the variable from $candiate to something like $child, since at the time it gets assigned a value in the foreach loop, you don’t know whether its actually a Candidate node yet … but that is a rather philosophical aspect.)

foreach loop in while loop with div inside list element

hello guys i am trying to make a foreach loop in a while loop. in foreach loop i try to produce list elements with divs inside them but i have very strange output
here is my code
$countercat= 0;
$classvar= 1;
echo "<div class='selector-page'>";
echo "<div class='selector'>";
echo "<ul>";
while ($countercat <= 8){
$stmt=$conn->prepare('SELECT eidos, name, meta_keys, address, telephone, perioxi, st_img, st_open, st_close, lat, longtit FROM magazia WHERE perioxi= :perioxi AND eidos= :eidos ORDER BY st_id ASC');
$stmt->bindParam(':perioxi', $name, PDO::PARAM_STR);
$stmt->bindParam(':eidos', $eidos, PDO::PARAM_STR);
$eidos= $c_titles[$countercat]['c_name'];
$stmt->execute();
$allrows=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($allrows as $row) {
echo "<li>";
echo "<div class='p". $classvar . " w3-card targetDiv w3-margin-top cardsmar'>";
echo "<img src='../uploads/" . $row['st_img'] . "' class='cccard' alt='" . $row['name'] . "'";
echo "<div class='w3-container w3-center'>";
echo "<h3>" . $row['name'] ."</h3>";
echo "<p>" . $row['eidos'] . "</p>";
echo "<p>" . $row['address'] . " , " . $row['perioxi'] . "</p>";
echo "<p>" . $lang['wrlt'] . " : " . $row['st_open'] . "-" . $row['st_close'] . "</p>";
echo "<a href='katastimata.php?name=" . $row['name'] . "' role='button' class='w3-button w3-round w3black'>" . $lang['t9'] . "</a><br />";
echo "<a href='https://www.google.com/maps?q=loc:" . $row['lat'] . "," . $row['longtit'] . "' role='button' class='w3-button w3-round w3-green btnmar'>" . $lang['spot2'] . "</a>";
echo "</div>";
echo "</div>";
echo "</li>";
}
$countercat++;
$classvar++;
}
echo "</ul>";
echo "</div>";
echo "</div>";
}
?>
here is an image from my debugger consonle
as you see in the image inside in the ul tag exists only one li elemenemt
and the rest of them are out side ul /ul.
my first thought was that is not valid to put div tag in a li tag but this is not true if i use this in the top of my file
DOCTYPE html PUBLIC "-//W3C// DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/html1-transitional.dtd"
html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang:"en"
i am stack here for so long
what am i missing guys?
thanks in advance
vaggelis
You Didn't Close the <img> tag here.
echo "<img src='../uploads/" . $row['st_img'] . "' class='cccard' alt='" . $row['name'] . "'";
You Must Close the tag as
echo "<img src='../uploads/" . $row['st_img'] . "' class='cccard' alt='" . $row['name'] . "'/>";

Add an increasing counter in a PHP table for a shopping cart

I have written a code for shopping cart and wanted to add numbers 1, 2, 3, etc. before each product in a table.
How to add counter inside <th>x</th>?
Full code of table below:
<?php
if ($obj_cart->items) {
echo("<form action='" . BASE_URL . "products/process/process_cart.php' method='post'>"
. "<table class='table table-hover' width='650px' border='1px' bordercolor='black' cellspacing='0' cellpadding='0'>");
echo("<thead>"
. "<tr align='right'>"
. "<th>x</th>" //here i want to add 1, 2 ,3 . untill products add. how to add loop
. "<th>Product Name</th>"
. "<th>View Details</th>"
. "<th>Unit Price</th>"
. "<th>Quantity</th>"
. "<th>TOTAL</th>"
. "</tr>"
. "</thead>");
foreach ($obj_cart->items as $item) {
echo("<tbody>"
. "<tr align='center'>"
. "<td><a href='" . BASE_URL . "products/process/process_cart.php?action=remove_item&productID=$item->itemID'>X</a></td>"
. "<td>$item->item_name</td>"
. "<td><a href='" . BASE_URL . "products/product_detail.php?productID=$item->itemID' target='_blank'>View Details</a></td>"
. "<td>$item->unit_price</td>"
. "<td><input class='box' type='text' value='$item->quantity' name='qtys[$item->itemID]'></td>"
. "<td>$item->total_price</td>"
. "</tr>"
. "</tbody>");
}
echo("<thead>"
. "<tr align='center'>"
. "<th><a href='" . BASE_URL . "products/products.php'><input class='btn btn-default' type='button' value='Shop More' /></a></th>"
. "<th><a href='" . BASE_URL . "products/process/process_cart.php?action=empty_cart'><input class='btn btn-default' type='button' value='Empty Cart' /></a></th>"
. "<th>"
. "<input type='hidden' name='action' value='update_cart'>"
. "<input type='submit' class='btn btn-default' value='Update Cart'>"
. "</th>"
. "<th>Check Out</th>"
. "<th>TOTAL</th>"
. "<th>$obj_cart->total_price</th>"
. "</tr>"
. "</thead>");
echo("</table></form>");
} else {
echo("<label>Your cart is empty</label>");
}
?>
If I understood you correctly, you need something like this. You need to add a counter that will track the number of currently displayed product so you may print its value wherever you want:
$counter = 1; // initial value
foreach ($obj_cart->items as $item) {
echo("<tbody>"
. "<tr align='center'>"
. "<td><a href='" . BASE_URL // the counter is displayed in the next line
. "products/process/process_cart.php?action=remove_item&productID=$item->itemID'>" . $counter . ". X</a></td>"
. "<td>$item->item_name</td>"
. "<td><a href='" . BASE_URL . "products/product_detail.php?productID=$item->itemID' target='_blank'>View Details</a></td>"
. "<td>$item->unit_price</td>"
. "<td><input class='box' type='text' value='$item->quantity' name='qtys[$item->itemID]'></td>"
. "<td>$item->total_price</td>"
. "</tr>"
. "</tbody>");
$counter++; // update counter value on each product
}
$counter = 0;
foreach ($obj_cart->items as $item) {
$counter++;
echo("<tbody>"
. "<tr align='center'>"
. "<td> $counter <a href='" . BASE_URL . "products/process/process_cart.php?action=remove_item&productID=$item->itemID'>X</a></td>"
. "<td>$item->item_name</td>"
. "<td><a href='" . BASE_URL . "products/product_detail.php?productID=$item->itemID' target='_blank'>View Details</a></td>"
. "<td>$item->unit_price</td>"
. "<td><input class='box' type='text' value='$item->quantity' name='qtys[$item->itemID]'></td>"
. "<td>$item->total_price</td>"
. "</tr>"
. "</tbody>");
}

'Unexpected echo' PHP error message - outputting php variable in html input 'value' field [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I keep on receiving this error message when running the PHP code below ::
"Parse error: syntax error, unexpected 'echo' (T_ECHO) in
C:\xampp\htdocs\informationdb\item.php on line 93"
I am trying to output dynamic PHP variables in a static html table using a foreach loop. By any chance, can anyone spot where the error lies?
My code is as follows::
<table>
<form action='', method="POST">
<?php
foreach($libitem["libraries"] as $library) {
foreach($libitem["libraryitemids"] as $libraryitemid) {
foreach($libitem["sectionnames"] as $sectionName) {
foreach($libitem["sectionnumbers"] as $sectionNumber) {
echo "<tr><td id='radiocell'><input type='radio' name='libraryitemid' id='radio' value='" . $libraryitemid . "'></td><td>" . echo $library . "</td><td>" . echo $sectionName . "</td><td>" . echo $sectionNumber . "</td><td class='available'>Available</td></tr>";
}
}
}
}
?>
</table>
When you are concatenating a string, you use dots, but no echo, also see the manual:
echo "<tr><td id='radiocell'><input type='radio' name='libraryitemid' id='radio' value='" . $libraryitemid . "'></td><td>"
. echo $library . "</td><td>"
. echo $sectionName . "</td><td>"
. echo $sectionNumber . "</td><td class='available'>Available</td></tr>";
should be:
echo "<tr><td id='radiocell'><input type='radio' name='libraryitemid' id='radio' value='" . $libraryitemid . "'></td><td>"
. $library . "</td><td>"
. $sectionName . "</td><td>"
. $sectionNumber . "</td><td class='available'>Available</td></tr>";
Don't use echo here
. echo $library . "</td><td>" . echo $sectionName . "</td><td>" . echo $sectionNumber . "
There is need only first echo.
For concatenation isn't necessary.
Remove echo from inside the string.
For example,
" . $libraryitemid . "'></td><td>" . echo $library . "</td><td>" . echo $sectionName .
shoule be
" . $libraryitemid . "'></td><td>" . $library . "</td><td>" . $sectionName . "<
Try this:
echo "<tr><td id='radiocell'><input type='radio' name='libraryitemid' id='radio' value='" . $libraryitemid . "'></td><td>" . $library . "</td><td>" . $sectionName . "</td><td>" . $sectionNumber . "</td><td class='available'>Available</td></tr>";
you are using echo in the echo which is an error .
remove this line .
echo "<tr><td id='radiocell'><input type='radio' name='libraryitemid' id='radio' value='" . $libraryitemid . "'></td><td>" . echo $library . "</td><td>" . echo $sectionName . "</td><td>" . echo $sectionNumber . "</td><td class='available'>Available</td></tr>";
you should use this
<table>
<form action='', method="POST">
<?php
foreach($libitem["libraries"] as $library) {
foreach($libitem["libraryitemids"] as $libraryitemid) {
foreach($libitem["sectionnames"] as $sectionName) {
foreach($libitem["sectionnumbers"] as $sectionNumber) {
echo "<tr><td id='radiocell'><input type='radio' name='libraryitemid' id='radio' value='" . $libraryitemid . "'></td><td>" . $library . "</td><td>" . $sectionName . "</td><td>" . $sectionNumber . "</td><td class='available'>Available</td></tr>";
}
}
}
}
?>
</table>

PHP How to echo a different image every 10th row of my results

I have a simple search engine which echo's out results in a table with CSS formatting, this is working fine, however, i would now like to echo a different image after every 10 results.
thankyou to any one who can help me as I have been stuck on this for hours!
this is my echo output code:
echo "<table width='50%' style='border-bottom:1px solid #000000;'";
echo "<tr>";
echo "<td>";
echo "<div id='page-wrap'>";
echo "<div class='discounted-item freeshipping'>";
echo "<a href='./img/users/" . $row['category'] . "/" . $row['username'] . "/" . $row['filename'] . "' rel='lightbox'><img src=\"./img/users/" . $row['category'] . "/" . $row['username'] . "/" . $row['filename'] . "\" alt=\"\" width='20%' height='98%' /></a>";
echo "<div class='reasonbar'><div class='prod-title' style='width: 70%;'>" .$row['fname'] . "</div><div class='reason' style='width: 29%;'><b>". $row['firstname'] . " " . $row['surname'] ."</b></div></div>";
echo "<div class='reasonbar'><div class='prod-title1' style='width: 70%;'>" . $row['lname'] . "</div><div class='reason1' style='width: 29%;'>Category: ". $row['category'] . "</div></div>";
echo "<div class='reasonbar'><div class='prod-title2' style='width: 70%;'>Contact:" . $row['contact'] . "</div><div class='reason2' style='width: 29%;'>Price: £". $row['price'] . "</div></div>";
echo "</td>";
echo "</tr>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
}
else
echo "No results found for \"<b>$search</b>\"";
You can use modolus operator to determine that...
if ( ! ($i % 10)) {
// Alternate.
}
If you don't have a counter variable at your disposal, just declare one outside of your loop and set it to 0 and increment it for each iteration.

Categories