I have a script which loads items from an XML file, and displays them, so a user can choose which item they want to remove from their file. Here's the PHP:
<?php
global $current_user;
get_currentuserinfo();
$userid= $current_user->ID;
$dom = new DOMDocument;
$dom->load("playlists/$userid.xml");
echo '<div class="styled-select">';
echo '<center><form name="input" action="/remove/removesure.php" method="get">';
echo '<select name="q[]" size="2" multiple>';
$titles = $dom->getElementsByTagName('title');
foreach ($titles as $title) {
echo '<option>'.$title->nodeValue.'</option>';
}
echo '</select>';
echo '<input type="submit" class="submit" value="Remove">';
echo '</form></center>';
echo '</div>';
?>
The problem I've ran into is that it doesn't display some objects correctly, mainly items with hyphens (it displays – instead of -) and titles with spaces at the end, and because of this, my removal code doesn't find the item, and so can't remove it. I don't know what to do, and I don't know why it's doing this. I'm running the code in wordpress, if that makes a difference.
Any ideas?
If there is no chance of having any kind of councurrency, I would suggest you to use the title index of the title tag as value of "option". Eg:
$titles = $dom->getElementsByTagName('title');
$counter = 0;
foreach ($titles as $title) {
echo '<option value='.$counter.' >'.$title->nodeValue.'</option>';
$counter++;
}
In removesure.php, you could handle this by using an XPath expression like the next one:
//Title[2]
where "2" is the index of the title that must be removed.
That is a possible solution; another path you could try to follow is to handle spaces providing the best encoding option for your titles. htmlentity is the function that you should execute
echo '<option>'.htmlentity($title->nodeValue).'</option>'
Related
Using Xpath, I'm extracting some data from an HTML page. I've the below portion in my code:
echo '<ol type="A">';
foreach ($options as $option) {
echo '<li>'.$option->nodeValue.'</li>';
}
echo '</ol>';
Result is
A. some text
B. some other text
C. a different text
D. yet another text
I want to manually copy the output to a text file. When I do that, the prefixes (A., B.,C,D.) are not copied from browser to text file. So I want to add the prefixes A,B,C,D to my $option->nodeValue inside the foreach loop (always 4 members in the array)- instead of using li tag. How can I do that? (or is there a way to simple copy from browser with the li tag output :) )
YOu mean like this?
$letters=['A','B','C','D'];
echo '<ol type="A">';
foreach ($options as $index=>$option) {
echo '<li>'.$letters[$index] . " " . $option->nodeValue.'</li>';
}
echo '</ol>';
I'm trying to get wordpress to show tag if there is a tag. but when there is no tag, other element are affected and hidden if there is no tag. I want it to show "No tag Available", when there is no tag, not hiding the whole element.
if ( !has_tag() ) return;
$tags = get_the_tags();
foreach ( $tags as $tag ) {
$tag_link = get_tag_link( $tag->term_id );
}
echo "<li class='list-group-item'><a href='{$url}' class='btn btn-danger btn-sm'><strong>Original Size</strong> ({$original_w}x{$original_h})</a> <a href='{$tag_link}' class='btn btn-danger btn-sm'><strong>Show more {$tag->name} wallpaper</strong></a></li>";
When there is a tag in the post
http://i.stack.imgur.com/Tl06G.png
When there is no tag in the post
http://i.stack.imgur.com/jUyAZ.png
I want to show the elements even where there is no tag in the post.
FYI, I newbie to PHP.
Your code is just a bit scrambled here. You need to check if $tags is empty or not. $tags will be empty if there is no tags, which means get_the_tags returns an empty array.
You can do something like this
$tags = get_the_tags();
if($tags) {
//your foreach loop to show tags
}else{
// show something else if there are no tags
}
You can do something like this. this worked for me.
<div class="post-tags">
<?php
global $post;
if(has_tag()){
foreach(get_the_tags($post->ID) as $tag)
{
echo '' . $tag->name . '';
}
}else{
echo 'No tags available';
}
?>
</div>
You have already received good answers, I'd like to add something general:
You can also use the PHP function count() to count the number of items in an array. This will give you a somewhat more precise information and not only "has tags" or "has no tags".
If you save the result of count() in a variable, you can use it in conditional statements like switch or if-clauses, like already shown.
I have this scenario:
<div class="listing_title">
<strong>
<a href="http://www.mywebsite.com/dectails23291.html" id="url_id_1977">
Listing Title
</a>
</strong>
</div>
To get Listing Title, I have implemented this code:
$page = "http://www.mywebsite.com/listings.html";
$html = new simple_html_dom();
$html->load_file($pagina);
foreach($html->find('.listing_title') as $element)
echo $element->first_child()->plaintext . '<br>';
OUTPUT IS:
Listing Title
Now I need get id value
url_id_1977
preferably only "1977", clean of "url_id_", but I dont know do. Thanks in advance!!
Add this inside of your foreach loop:
echo end(explode('_', $element->find('a', 0)->id));
To get rid of the warning you could assign the id to a variable:
$id = explode('_', $element->find('a', 0)->id);
echo $id[2];
Or, if your anchor's id always starts with url_id_, just use str_replace():
echo str_replace('url_id_', '', $element->find('a', 0)->id);
try this
foreach($html->find('*[class=listing_title] a') as $element)
echo $element->id. '<br>';
Here's the problem, I am trying to echo a statement or an array after dynamically generated HTML, and unfortunately the thing that i want to echo goes above the HTML, is there any way to echo it after that dynamic HTML or work around?
Code:
Link 1
Link 2
if(isset($_GET["id"]) && $_GET["id"] == "do_something") {
$html = "dynamic html generate";
echo $html;
//after this im using foreach
foreach($array as $item) { echo $item . "<br />"; }
}
As I click one of these two , dynamically generated HTML shows up. Now for example I have an array:
$array = array("error1", "error2");
All the generated PHP goes above the dynamic HTML :/.
How should i fix it so that i can echo all of this array below the dynamic HTML?
Thanks
Use buffering with ob_start
ob_start();
// dynamic html code generate
$dynamic_html = ob_get_clean();
echo $dynamic_html;
// your code
echo $dynamic_html;
Sounds like you missed some closing tags (most likely </table>) in the dynamic html. Thats why the later generated echo gets displayed at the top.
Example (Note the missing closing table):
<?php
echo "<table><tr><td>TableText</td></tr>";
echo "I should be bellow the table, but going to the top.";
?>
will produce:
I should be bellow the table, but going to the top.
TableText
while($row = mysql_fetch_array($result))
//Template for each card in search result
{
echo '<div class="sleeve">';
echo '<div class="card ', $row['name'], '">';
echo '<div class="front face">';
echo '<img src="/', $row['cardset'], '/', $row['name'], $row['altart'], '.jpg"', ' alt="', $row['name'], '" />';
echo '</div>';
echo '<div class="back face">';
echo '<a id="name">', $row['name'], '</a><br/>';
echo '<form name="info" action="">';
echo '<select name="set">';
//while???
echo '<option value="Zendikar">', $row['sets'],'</option>';
echo '</select>';
echo 'Foil:<input type="checkbox" name="foil" value="true"/><br/>';
echo '<select name="condition">';
echo '<option value="Near Mint">Mint</option>';
echo '<option value="Played">Played</option>';
echo '<option value="Damaged">Damaged</option>';
echo '</select>';
echo 'Trade:<input type="checkbox" name="trade" value="true"/ <br/>';
echo '</form>';
echo '<b>Rulings:</b> <br/>';
echo $row['rulings'];
echo '</div>';
echo '</div>';
echo '</div>';
}
//while??? It might be hard to see in that mess of echoes, but there's a section that I have no idea how to deal with. PHP is grabbing rows of info, and populating them nicely. It fills the screen with little boxes of info.
In this section, that I don't know how to deal with, the data in one of the rows contains multiple things (thing1, thing2, thing3) separated by a (, ) each time. I need each of those things in a new thing1
So I feel like there would be another while loop inside each card?
You're on the right track with a loop. Try something like this, which explodes the string into an array, based on the comma delimiter, with explode():
echo '<select name="set">';
foreach( explode( ',', $row['sets']) as $item)
echo '<option>', $item, '</option>';
echo '</select>';
You probably need a foreach statement there after exploding the String into an array:
instead of the //while line and the following one:
foreach (explode(',', $row['sets']) as $value)
echo '<option value="', $value, '">', $value,'</option>';
I guess you may actually have another value for each row (one to be displayed, the other one is the actual value you want to set), but then the String would look much more like "(key1=value1, key2=value2)" and then you need a little more work, but you get the idea.
Hope this helps.
Yes, you would need to first explode that row into an array
$list_of_things = explode(",", $row['whatever']);
and then use a while, or a foreach:
$thing_options = '';
foreach($list_of_things as $thing)
$thing_options .= "<option>$thing</option>";
You might also find the here document syntax useful:
print <<<TEMPLATE
<div class="sleeve">
<div class="card {$row['name']}">
<div class="front face">
<img src="/{$row['cardset']}/{$row['name']}{$row['altart']}.jpg"
alt="{$row['name']}" />
</div>
<div class="back face">
<a id="name">{$row['name']}</a>
<br/>
<form name="info" action="">
<select name="set">
{$thing_options}
<option value="Zendikar">{$row['sets']}</option>
</select>
...
TEMPLATE;
While all of the answers telling you to explode() the array are correct, I can't help but think that having a db column filled with comma separated values are a symptom that your database is not normalized. You should check out the following link for an introduction to db normalization: http://mikehillyer.com/articles/an-introduction-to-database-normalization/
I'd also recommend not echoing out HTML. Ideally, your PHP scripts should follow this pattern:
All PHP processing up front, including database queries and form handling. Results should be stored in variables.
|
|
|
V
Almost pure HTML template/view, with just enough display logic (if/else, loops, echo) to actually display the results you stored in the variables from step 1.
You'll find that debugging/editing is a lot simpler if you let PHP be the brains and HTML be the beauty. Just like how markup and styles should be separate, the same goes for scripting and display.
You can use PHP's explode-method to split the comma separated string into its values, and then handle that array in a foreach loop:
$raw = "one,two,three";
$values = explode("," $raw);
foreach($values as $value) {
echo $value;
}