Find all like attributes in document, and change output based on value - php

I've been working on this list that will provide information from an xml file. The markup I'm working with is as follows:
<?php
$xml_file = '/path';
$xml = simplexml_load_file($xml_file);
foreach($xml->Continent as $continent) {
echo "<div class='continent'>".$continent['Name']."<span class='status'>".$continent['Status']."</span>";
foreach($continent->Country as $country) {
echo "<div class='country'>".$country['Name']."<span class='status'>".$country['Status']."</span>";
foreach($country->City as $city) {
echo "<div class='city'>".$city['Name']."<span class='status'>".$city['Status']."</span></div>";
}
echo "</div>"; // close Country div
}
echo "</div>"; // close Continent div
}
?>
What I'm trying to accomplish is changing the 'Status'. Regardless of the element, the 'Status' only has two values and will always be either "Red" or "Blue". What I'm trying to do is go through the whole document, find the "Status" attribute, see if the value is "Red", then display an icon or some text, but if it's blue, display nothing. I've come across different examples, but none that show this type of generality. Most of the examples were for locating a specific node and then displaying it's attributes. I'm also trying to avoid, if possible, having to create this rule within each loop, but instead applying it to the whole document (if this seems like the best method.)

Use css selectors instead of javascript. That will make your code lighter and simple!
For example:
<?php
$xml_file = '/path';
$xml = simplexml_load_file($xml_file);
foreach($xml->Continent as $continent) {
echo "<div class='continent'>".$continent['Name']."<span class='status ". cssForStatus($continent['Status'])."'></span>";
foreach($continent->Country as $country) {
echo "<div class='country'>".$country['Name']."<span class='status ". cssForStatus($country['Status'])."'></span>";
foreach($country->City as $city) {
echo "<div class='city'>".$city['Name']."<span class='status ". cssForStatus($city['Status'])."'></span></div>";
}
echo "</div>"; // close Country div
}
echo "</div>"; // close Continent div
}
function cssForStatus($status='')
{
switch ($status) {
case 'red':
$css = "red";
break;
default:
$css = "blue";
break;
}
return $css;
}
while your css can be:
span.status {
height: 10px;
width: 10px;
}
span.status.red {
background-color: "red";
}
span.status.blue {
background-color: "blue";
}
we are using the concept of multiple css classes

Just change your code slightly to add status as your div class.
Example:
echo "<div class='continent status-{$continent['Status']}'>{$continent['Name']}</div>";
This will output (in case of a red continent named Europe)
<div class='continent status-red'>Europe</div>
then add this CSS to your html:
.status-red {
background-color: red;
}
.status-blue {
background-color: blue;
}
Or somehting along these lines

Related

Letting CSS interact with HTML through PHP

The following is my PHP code:
$heads = array();
$heads[0] = "<p class='ourmoto'>Your camera solutions...</p>";
$heads[1] = "<a href='index.html'><img id='rentals' src='images/rentalsnew2.jpg' alt='GroupLogo' /></a>";
$heads[2] = "<p class='ourmoto'>...Your camera solutions</p>";
for ($i = 0; $i<3; $i++){
echo"<p>$heads[$i]</p>";
}
CSS:
.ourmoto {
font-style:oblique;
font-size:30px;
display:inline;
margin: 0 auto;
}
From my knowledge, echo should print whatever comes after it in a quote as a string, even if its HTML tags. It manages to print the HTML but CSS won't apply on it. What am I doing wrong?
Thank you!
Iterate through each heads, echo paragraph with class:
foreach ($heads as $head)
echo "<p class='ourmoto'>{$head}</p>";
}

line break after each row retrieval

I need to add a line break after each row retrieved;
I hav tried adding in every possible way.. No luck..
while ($line = mysql_fetch_array($result))
{
?>
<style>
.whiteBackground { background-color:#F5ECCE;float:left;}
.grayBackground { background-color:#CED8F6; float:right;}
.date { font-size:10px; color:#627d79;float:right}
</style>
<?php
$sender=$line["sender"];
$classy=($sender == $uid)? 'whiteBackground': 'grayBackground';
$q=mysql_query("select * from users where u_id='$sender'");
$row=mysql_fetch_array($q);
$receiver=$row['firstname'];
//if($receiver!= $line["receiver"])
$msg = $msg . "<tr class='$classy'>" .
"<td>" . $receiver . ": </td>" .
"<td>" . $line["msg"] . "</td>"."<td class='date'>" . $line["chattime"] . "</td></tr>";
}
$msg=$msg . "</table>";
echo $msg;
I need to add a break after each sender+msg+time.//like in a usual chat.
Your problem come from float declarations. They are useless in your code :
.whiteBackground { background-color:#F5ECCE;float:left;}
.grayBackground { background-color:#CED8F6; float:right;}
.date { font-size:10px; color:#627d79;float:right}
Remove them and it will work as expected.
You don't need them in your code if you use <table> and <tr>. Default behaviour of <tr> is to create a new "line" each time you add it, but with adding float you're breaking this behaviour.
Also, follow #bulforce recommendation to move your CSS before loop : your code add it as many time you have messages in your document (if you have 10 messages, css declarations will be added 10 times).
<style type="text/css">
.whiteBackground { background-color:#F5ECCE; }
.grayBackground { background-color:#CED8F6; }
.date { font-size:10px; color:#627d79; }
</style>
<?php
while ($line = mysql_fetch_array($result))
{
// ...
}
?>
Just try to add a <tr><td colspan="3"> </td></tr> after </tr> inside the while loop
First consider moving the css declaration before the loop, there is no point to have it in the loop body.
Second the second query in the loop should also be moved before the loop and rework this a bit.
Now to your question, one option would be to change the table with divs and spans.. something like so:
<div class="message-row">
<span class="message-user">Name</span>
<span class="message-text">Message</span>
</div>
Then style as you did before, and add margin-bottom: 15px; to the message-row definition.
before while
$msg="<table>";
Inside while
$msg.= "<tr class='$classy'>" in place of $msg = $msg . "<tr class='$classy'>"
Will work for you.
I solved it by replacing table tags with div tags.
Thnku #bulforce; now I will completely follow ur recommendations.
$msg="<div>";
$date_temp="nil";
while ($line = mysql_fetch_array($result))
{
?>
<style>
.whiteBackground { background-color:#F5ECCE;float:left;}
.grayBackground { background-color:#CED8F6; float:right;}
.date { font-size:10px; color:#627d79;float:right}
</style>
<?php
$sender=$line["sender"];
$classy=($sender == $uid)? 'whiteBackground': 'grayBackground';
$q=mysql_query("select * from users where u_id='$sender'");
$row=mysql_fetch_array($q);
$receiver=$row['firstname'];
//if($receiver!= $line["receiver"])
/*if($date_temp!=$line["chatdate"]){
$date_temp=$line["chatdate"];
$msg=$msg.$line["chatdate"];
}*/
$msg = $msg . "<div class='$classy'>" . $receiver.": " . $line["msg"] ."<div class='date'>" . $line["chattime"] . "</div></div></br></br>";
}
$msg=$msg . "</div>";
echo $msg;

PHP list highlight current item

I have a ul list that is rendered in PHP and I am trying to highlight the current selected item. The code is part of a tag sorting jquery portfolio. I have tried to add a current class to the li element but that only works for the default element "All".
PHP-code
if ($unique_tags_arr) {
echo '<ul class="jquery">';
echo '<li data-filter=".filterable">';
echo "All";
echo '</li>';
foreach ($unique_tags_arr as &$value) {
echo '<li data-filter=".'.str_replace(' ', '', $value). " " .'"> '.$value.'</li>';
}
echo '</ul>';
}
Try this
jQuery(document).on("click", "ul.jquery > li", function() {
var $this = jQuery(this);
jQuery(".highlight").removeClass("highlight");
$this.addClass("highlight");
});
and then write a css rule for the highlight class
You can try with the following css style.
.jquery li:hover
{
color: #000;
background: #fff
}
I'm guessing there's no page load when filtering because your list items have the data-filter attribute and therefore I'd guess it's using jQuery. Then you should use something like gbestard suggested.
But if there's page load and you are using PHP on this like your tags say... You'll need the selected item value stored somewhere (POST, GET etc.) and with your stored selected item you need to compare if any of the array items has the same value and if it is, just add class "selected".
This is with GET so your selected value would be in the url.
$active = $_GET['selected_filter'];
if ($unique_tags_arr) {
echo '<ul class="jquery">';
echo '<li data-filter=".filterable">';
echo "All";
echo '</li>';
foreach ($unique_tags_arr as &$value) {
echo '<li data-filter="'.str_replace(' ', '', $value).'" ';
if ($value == $active) { echo 'class="selected"'; }
echo '> '.$value.'</li>';
}
echo '</ul>';
}
Then just give styles to the .selected class.

Giving a CSS Class to Echoing Strings

I've a PHP file which has numerous echo statements for various checks like this;
if ($power != "1")
{
echo "Please contact administrator for assistance.";
exit;
}
if (!$uid)
{
echo "You do not have permissions to change your status.";
exit;
}
if (!$mybb->input['custom'])
{
echo "You've not added any status to change";
exit;
}
I want to give a similar CSS class to each echo statement. I tried this;
if ($power != "1")
{
echo "<div class='class_name'>Please contact administrator for assistance.</div>";
exit;
}
and it works, but my php file has dozens of echo's and I don't want to edit each and every echo statement. Is there any easy way to achieve this?
You could define a function to handle outputting the message. You'll have to update the existing code but in the future, you'll be able to change the CSS class name or HTML structure easily be modifying the function.
class Response
{
public static function output($message, $className = 'class_name')
{
echo "<div class='" . htmlspecialchars($className) . "'>" . $message. "</div>";
exit;
}
}
Usage:
if ($power != "1")
{
Response::output("Please contact administrator for assistance.");
}
Override the class name:
Response::output("Please contact administrator for assistance.", "other_class");
If you're having issues/errors in above answers then here is my answer, I hope it helps;
Add the following code just above the <?php of your PHP file;
<style type="text/css">
.error{
background: #FFC6C6;
color: #000;
font-size: 13px;
font-family: Tahoma;
border: 1px solid #F58686;
padding: 3px 5px;
}
</style>
Next change each echo statement to something like this;
echo "<div class='error'>Write error code here.</div>";
exit;
You can easily find and replace the echo statements if you're using Notepad++
It should work. Also its somewhat similar to MrCode's answer however I think my answer is easily understandable and may be easy to implement.
There's no there way, unless you define once css class and put all your echo statements inside it.
<div class = "name">
<?php
echo ...
...
...
?>
</div>
Try to change each echo to a fixed variable name:
if ($power != "1")
{
$msg = "Please contact administrator for assistance.";
}
if (!$uid)
{
$msg = "You do not have permissions to change your status.";
}
if (!$mybb->input['custom'])
{
$msg = "You've not added any status to change";
}
Then write a function for giving style to the out put:
function stylizing($msg, $class="")
{
if($class != "")
$msg = "<div class='{$class}'>{$msg}</div>";
echo $msg;
}
Then you can use stylizing($msg, "class_name"); where you want to print out the result.
Do you mean something like this?
$message = '';
if ($power != "1") $message .= "<div class='one'>Please contact administrator for assistance.</div>";
elseif (!$uid) $message .= "<div class='two'>You do not have permissions to change your status.</div>";
elseif (!$mybb->input['custom']) $message .= "<div class='three'>You've not added any status to change.</div>";
echo $message;

insert echo into the specific html element like div which has an id or class

I have this code.
<html>
<head>
<style type="text/css">
body{background:#666666;}
div{border:1px solid red;}
</style>
</head>
<body>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM hi");
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
mysql_close($con);
?>
</body>
</html>
the above code works.
now, I want to insert this
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
into the specified div or other element in the html, example, i will insert this
echo '<img src="'.$row['name'].'" />';
into the html element .
I dont know how to do this, please help me. Thanks
Juliver
if yo want to place in an div like
i have same work and i do it like
<div id="content>
<?php
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
?>
</div>
The only things I can think of are
including files
replacing elements within files using preg_match_all
using assigned variables
I have recently been using str_replace and setting text in the HTML portion like so
{{TEXT_TO_REPLACE}}
using file_get_contents() you can grab html data and then organise it how you like.
here is a demo
myReplacementCodeFunction(){
$text = '<img src="'.$row['name'].'" />';
$text .= "<div>".$row['name']."</div>";
$text .= "<div>".$row['title']."</div>";
$text .= "<div>".$row['description']."</div>";
$text .= "<div>".$row['link']."</div>";
$text .= "<br />";
return $text;
}
$htmlContents = file_get_contents("myhtmlfile.html");
$htmlContents = str_replace("{{TEXT_TO_REPLACE}}", myReplacementCodeFunction(), $htmlContents);
echo $htmlContents;
and now a demo html file:
<html>
<head>
<style type="text/css">
body{background:#666666;}
div{border:1px solid red;}
</style>
</head>
<body>
{{TEXT_TO_REPLACE}}
</body>
</html>
You can write the php code in another file and include it in the proper place where you want it.
AJAX is also used to display HTML content that is formed by PHP into a specified HTML tag.
Using jQuery:
$.ajax({url: "test.php"}).done(function( html ) {
$("#results").append(html);
});
Above code will execute test.php and result will be displayed in the element with id results.
There is no way that you can do it in PHP when HTML is already generated. What you can do is to use JavaScript or jQuery:
document.getElementById('//ID//').innerHTML="HTML CODE";
If you have to do it when your URI changes you can get the URI and then split it and then insert the HTML in script dynamically:
var url = document.URL;
// to get url and then use split() to check the parameter
refer to the basic.
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
there is no way to specifically target an element with php, you can either embed the php code between a div tag or use jquery which would be longer.
You can repeat it by fetching again the data
while($row = mysql_fetch_assoc($result)){
//another html element
<div>$row['name']</div>
<div>$row['title']</div>
//and so on
}
or you need to put it on the variable and call display it again on other html element
$name = $row['name'];
$title = $row['title']
//and so on
then put it on the other element, but if you want to call all the data of each id, you need to do the first code
Have you tried this?:
$string = '';
while($row = mysql_fetch_array($result))
{
//this will combine all the results into one string
$string .= '<img src="'.$row['name'].'" />
<div>'.$row['name'].'</div>
<div>'.$row['title'].'</div>
<div>'.$row['description'].'</div>
<div>'.$row['link'].'</div><br />';
//or this will add the individual result in an array
/*
$yourHtml[] = $row;
*/
}
then you echo the $tring to the place you want it to be
<div id="place_here">
<?php echo $string; ?>
<?php
//or
/*
echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
*/
?>
</div>
Well from your code its clear that $row['name'] is the location of the image on the file, try including the div tag like this
echo '<div>' .$row['name']. '</div>' ;
and do the same for others, let me know if it works because you said that one snippet of your code is giving the desired result so try this and if the div has some class specifier then do this
echo '<div class="whatever_it_is">' . $row['name'] . '</div'> ;
You have to put div with single quotation around it. ' ' the Div must be in the middle of single quotation . i'm gonna clear it with one example :
<?php
echo '<div id="output">'."Identify".'<br>'.'<br>';
echo 'Welcome '."$name";
echo "<br>";
echo 'Web Mail: '."$email";
echo "<br>";
echo 'Department of '."$dep";
echo "<br>";
echo "$maj";
'</div>'
?>
hope be useful.
I use this or similar code to inject PHP messages into a fixed DIV positioned in front of other elements (z-index: 9999) just for convenience at the development stage.
Each PHP message passes into my 'custom_message()' function and is further conveyed into the innard of preformatted DIV created by echoed JS.
There can be as many as it gets, all put inside that fixed DIV, one under the other.
<style>
#php_messages {
position: fixed;
left: 0;
top: 0;
z-index: 9999;
}
.php_message {
background-color: #333;
border: red solid 1px;
color: white;
font-family: "Courier New", Courier, monospace;
margin: 1em;
padding: 1em;
}
</style>
<div id="php_messages"></div>
<?php
function custom_message($output) {
echo
'
<script>
var
el = document.createElement("DIV");
el.classList.add("php_message");
el.innerHTML = \''.$output.'\';
document.getElementById("php_messages").appendChild(el);
</script>
';
}
?>

Categories