Ignoring data when using SimpleXML to list children - php

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.)

Related

Reverse read xml file in 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.

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'] . "'/>";

missing data from mysql database

I have a mysql database that is used by a php script to display data... the problem i have is, at what appears to be random occurrences it misses results and I can't see a pattern to establish why it might be doing it...
all the data appears to be fine when i check the database.
here is my initial search page
<?php
include 'connect.php';
//set variable
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
echo "<html xmlns='http://www.w3.org/1999/xhtml'>";
echo "<title>HSB - Latest Offers</title>";
echo "<style type='text/css'>;
body {
background-color: #FFF;
}
#wrapper {
background-color: #FFF;
height: auto;
width: 1000px;
margin-right: auto;
margin-left: auto;
font-family: 'Trebuchet MS', Arial, Helvetica, sans-serif;
}
</style>
</head>
<body>
<div id='wrapper'>
<p><img src='images/header.jpg' width='400' height='100' alt='header' /></p>
<HR/>
Select an area from the menu below to view any offers in that area.
<form id='filter' name='filter' method='post' action='resultssimple.php'>
<p><label>County</label></p>
<select name='result' id='result'>' . $option . '</select>
<input name='' type='submit' />
</form>
</div>
</body>
</html>";
?>
and here is my results page
<?
include 'connect.php';
//Get the details from previous page
$SelectedCounty = $_POST["result"];
// Select offers linked to selected county from form
$result = mysqli_query($con,"SELECT * FROM offers WHERE tradingCounty ='" . $SelectedCounty . "'ORDER BY categoryIdName ASC;");
// PREVIOUS ATTEMPTS - ALL WRONG - GGGGRRRRRRRRRRRR !!!!!!!!
//------------------------------------------------------------
//$result = mysqli_query($con,"SELECT * FROM offers WHERE tradingCounty LIKE" . $SelectedCounty);
//$result = mysql_query("SELECT * FROM pdetails WHERE uid='" . $inputname . "';");
//"SELECT * FROM `offers` WHERE `tradingCounty` LIKE
//$result = mysqli_query($con,"SELECT * FROM offers;");
//$result = mysql_query("SELECT * FROM pdetails WHERE uid='" . $inputname . "';");
//$result = mysqli_query("SELECT * FROM offers WHERE tradingCounty=" . $SelectedCounty);
//check to see if results is set - error if not.
if(!$result)
{
die("<p>Error in listing tables: ". mysql_error()."</p>");
}
//Show all records for selected county
echo ("<p><h2>Showing Latest Offers In : " . $SelectedCounty . "</h2></p>");
echo ("<p><a href='offers.php' target='_self'>back to search menu</a></p>");
/*
echo ("<table border='1'>");
echo ("<tr>");
echo ("<td>ID</td><td>Category</td><td>Business Name</td><td>Business Address</td><td>Address2</td><td>Address3</td><td>Town</td><td>County</td><td>Post Code</td><td>Telephone</td><td>URL</td><td>Email</td><td>Discount / Special Offer</td><td>valid from</td>");
*/
while($row = mysqli_fetch_row($result))
{
echo ("<div style=' background-color: #EFF5FF; color: #06C; padding: 5px; float: left; border: 1px dotted #06C; margin: 10px; width: 300px; height: 300px; text-align: center; >");
// echo ("" . $row[0] . "");
// echo ("</br>");
echo ("<strong>" . $row[1] . "</strong>");
echo ("<hr/>");
// echo ("</br>");
echo ("" . $row[2] . "");
echo ("</br>");
echo ("" . $row[3] . "");
echo ("</br>");
// echo ("" . $row[4] . "");
// echo ("</br>");
// echo ("" . $row[5] . "");
// echo ("</br>");
echo ("" . $row[6] . "");
echo ("</br>");
echo ("" . $row[7] . "");
echo ("</br>");
echo ("" . $row[8] . "");
echo ("</br>");
echo ("" . $row[9] . "");
echo ("</br>");
// echo ("" . $row[10] . "");
// echo ("</br>");
echo ("" . $row[11] . "");
echo ("</br>");
echo ("<hr/>");
echo ("<strong>" . $row[12] . "</strong>");
echo ("</br>");
echo ("</div>");
/* echo("<tr>");
echo("<td>" . $row[0] . "</td>" . "<td>" . $row[1] . "</td>" . "<td>" . $row[2] . "</td>" . "<td>" . $row[3] . "</td>" . "<td>" . $row[4] . "</td>" . "<td>" . $row[5] . "</td>" . "<td>" . $row[6] . "</td>" . "<td>" . $row[7] . "</td>" . "<td>" . $row[8] . "</td>" . "<td>" . $row[9] . "</td>" . "<td>" . $row[10] . "</td>" . "<td>" . $row[11] . "</td>" . "<td>" . $row[12] . "</td>" . "<td>" . $row[13] . "</td>");
echo("</tr>");
*/
}
// echo("</table>");
?>
what I'm getting can be seen here
Are they missing or maybe they are obscured by unescaped html characters. Check the View Source option of your browser to see if they are actually there. I would especially watch for characters in the data like the Less Than character that the browser may be mistaking for an HTML open character.
You may need to escape your output so the browser does not try to render it:
echo ("" . htmlspecialchars($row[2]) . "");
Also, I would suggest you never take input directly from a user and put it into a SQL query without escaping it first. You are opening yourself up for SQL Injection attacks.
See the following:
http://php.net/manual/en/mysqli.real-escape-string.php
Don't know if it'll help but in this line:
$result = mysqli_query($con,"SELECT * FROM offers WHERE tradingCounty ='" . $SelectedCounty . "'ORDER BY categoryIdName ASC;");
it looks like you have an extra semi-colon (;) right before the last double quote. I don't think that should be there.
You could also store everything returned in an array and echo everything as you iterate through it to see what it returns. Then, if something's missing, go to your database and look at that row.
$tempArray = array();
while($row = mysqli_fetch_row($result)) {
$tempArray = $row;
}
foreach($tempArray as $value) {
echo $value . '<br>';
}

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.

Eliminating space between table data

I am trying to get rid of the border space between the cells. I thought cellspacing would do the trick but there is still a slim white border. Can anyone give me some advice...
<body>
<center><table style="cellspacing:0; width:400px; border:none;">
<?
echo "<tr><td> Team </td><td>Correct Picks</td><td>Points</td></tr>";
while($row = mysql_fetch_array($memberslist)) {
if ($row['User_ID'] == $id) {
echo "<tr bgcolor=\"gray\"><td>" . $row['User_ID'] . "</td><td><b>" . $row['Correct_Picks'] . " </b> /" . $maxcorrectpicks . "</td><td>" . $row['Points'] . "</td></tr>";
} else {
echo "<tr><td>" . $row['User_ID'] . "</td><td><b>" . $row['Correct_Picks'] . " </b> /" . $maxcorrectpicks . "</td><td>" . $row['Points'] . "</td></tr>";
}
}
?>
</table></center>
</body>
cellspacing=0;
is no CSS. That was once a HTML attribute:
<table cellspacing="0" style="width:400px">
See as well the related (duplicate?) question:
How to set cellpadding & cellspacing in CSS?

Categories