I have this website were you can order products.
The title of the products you can order are in HTML:
<div class="whatever"> Title </div>
I want to retrieve this "title" and set my php variable $product to the value "Title".
I have search a lot on the internet but somehow I am not able to find my answer.
How can I do it?
You can use \DOMDocument->loadHTML();
Ex:
<?php
$doc = new \DomDocument();
$doc->loadHTML('<div class="whatever"> Title </div>');
View examples here:
http://docs.php.net/manual/en/domdocument.loadhtml.php
This is assuming that your source is available to php. It would probably be more pragmatic to extract the value with javascript in the client and send it with the page request. If your app is well structured, the logic that renders the title into the page in the first place is probably where you should be looking to retrieve the information rather than trying to parse the html separately.
If you mean that you would like to do this from the client side, you should be using AJAX to achieve this. However, I think you mean that you want to put the HTML in a variable. That is very simple:
$variable = "<div class=\"whatever\"> Title </div>";
And to output the HTML:
echo $variable;
You can also add multiple elements to a single variable by concatting.
$variable = "";
$variable .= "<div class=\"whatever\"> Title </div>";
$variable .= "<div class=\"whatever\"> Another Title </div>";
echo $variable;
If you mean that you want to echo a variable within a dv, that works exactly the same way:
<div class="title"><?php echo $product; ?></div>
Or better looking:
<div class="title"><?= $product; ?></div>
Related
EDIT: I've updated this question with the working code, but I've left the content of the text alone so you can see what I was trying to do in the future and also because there were a few other things I wanted to do aside of the initial question.
I have an array that has an html list in it, the php is shuffling the list to echo a random order. Within the list items in the array, I want to include a php variable, right now this is what I have:
<?php include('includes/header_topright_content.php'); ?>
<ul data-options="animation:fade; slide_number:false; pause_on_hover:false; timer_speed:5500; navigation_arrows:false; next_on_click:true; timer:true; bullets:false;" data-orbit>
<?php
$links = array(
'<li data-orbit-slide="headline-1"><img /><div>'.$Slide1.'</div></li>',
'<li data-orbit-slide="headline-2"><img /><div>'.$Slide2.'</div></li>',
'<li data-orbit-slide="headline-3"><img /><div>'.$Slide3.'</div></li>',
);
shuffle($links);
foreach ($links as $link) { echo $link; }
?>
</ul>
I could have up to 10 or even 20 of these slides. The information the variables are linking to would be from a separate .php page that I "included." The information on that page is:
<?php
$Slide1 = "<h5>Slide 1</h5><h6>This is the content for slide 1!</h6>";
$Slide2 = "<h5>Slide 2</h5><h6>This is the content for slide 2!</h6>";
$Slide3 = "<h5>Slide 3</h5><h6>This is the content for slide 3!</h6>";
?>
If I scrap the variable idea and insert the html directly into the list item it works perfectly. If I try to put the variables in there, the slide will just be blank. I'm stuck on where to go from here, I'm great with html and css, but not so good with php, so any help is appreciated! I'm also open to any formatting tips and best practices, the cleaner the better.
Thanks in advance!
MORE INFO: There's a few complications behind as to why I'm looking to do this. The orbit image slider doesn't support a random order, and I found it much easier to just use php to randomize the order of the list items. The reason I want to use variables in these list items is because I'm using a cms (CouchCMS) to make that content editable - a simple solution would be to insert editable tags around that content, but that would only make one page editable, and this content is going to be 'included' in the header of every page. So I'm trying to find a way to put those variables on a separate page (I know 'including' it doesn't do that - maybe I can link it to the page like a css or js file?) to make that editable. If anyone has any ideas for this I'm open!
With string concatenation, your also need to include the variables file before assigning them variables to the array. You also dont need to wrap PHP variables in quotes when echoing.
<?php include('includes/variables.php'); ?>
<ul data-options="[orbit options go here]" data-orbit>
<?php
$links = array(
'<li data-orbit-slide="headline-1"><img /><div>'.$Slide1.'</div></li>',
'<li data-orbit-slide="headline-2"><img /><div>'.$Slide2.'</div></li>',
'<li data-orbit-slide="headline-3"><img /><div>'.$Slide3.'</div></li>',
);
shuffle($links);
foreach ($links as $link) { echo $link; } //<<< notice no quotes
?>
</ul>
Edit:
Can I make a suggestion to your code, by assigning to a slides array directly be it in an external file or not, you will be able to eventually dynamically or easily add new slides to the slider and not need to hard code into a second sub array before the loop. So something like. Also by changing to alternative syntax your keep a nice HTML structure.
<?php
$slide[] = "<h5>Slide 1</h5><h6>This is the content for slide 1!</h6>";
$slide[] = "<h5>Slide 2</h5><h6>This is the content for slide 2!</h6>";
$slide[] = "<h5>Slide 3</h5><h6>This is the content for slide 3!</h6>";
shuffle($slide);
?>
<ul data-options="animation:fade; slide_number:false; pause_on_hover:false; timer_speed:5500; navigation_arrows:false; next_on_click:true; timer:true; bullets:false;" data-orbit>
<?php foreach ($slide as $key=>$value):?>
<li data-orbit-slide="headline-<?php echo $key?>"><img /><div><?php echo $value; ?></div></li>
<?php endforeach;?>
</ul>
In PHP i'm using the following code to put a banner at the top of my website.
$eventinfo = simplexml_load_file("eventinfo.xml");
<div id="eventinfo"><?php foreach($eventinfo->children() as $child){ $final = $child["name"]."...<a href='".$child["adr"]."'>more info...</a>"; } ?>
</div>
The XML doc is available at the following: http://eastsidespeedway.raceresults.co/eventinfo.xml
If you go to http://eastsidespeedway.raceresults.co/index.php you'll see that the more info... link is showing up twice. One with the correct link, and the other with a link to the same page (index.php).
Can anyone shed some light on what I'm doing wrong?
Also. If you see anything that I'm doing wrong, or you know something that's easier - let me know! This is my first time using XML/PHP so I'm kinda just wingin it. Haha.
this will work for you
<?php
$doc = new DOMDocument();
$doc->load('http://eastsidespeedway.raceresults.co/eventinfo.xml');
$title = $doc->getElementsByTagName('title');
$link = $doc->getElementsByTagName('link');
//print_r($eventinfo);
?>
<div id="eventinfo">
<?php echo $title->item(0)->getAttribute('name'); ?>
<a href='<?php echo $link->item(0)->getAttribute('adr'); ?>'>More Infoo..</a>
</div>
If you look at your source:
<div id="eventinfo">5/18/2013 - Al Smiley Memorial...<a href=''>more
info...</a>...<a href='http://www.eastsidespeedway.com/dirt.html'>more
info...</a></div>
You've got two hyperlinks- one href is blank meaning that it will redirect to the current page, check your HTML code first to see if you've accidentally duplicated the element, otherwise look at the construction of your string in the php code
My website consists of many products that are each contained in a div with the id content block. The link, image, background, description and price are all loaded from a mySQL table. My original plan was to save the below html code as a string and loop over the rows in the mySQL table filling the string I created with php/mySQL values.
I was wondering if I am going about this the right way, or is there a better way to create html code from php variables?
<div id="contentblock" style="background-image:url(images/$BACKGROUND.png);">
<div id="picture"><img src="$IMAGELINK"/></div>
<div id="description"><p>$DESCRIPTION</p></div>
<div id="price"><p class=price>$PRICE</p></div>
</div>
Firstly PHP is a template engine - in my experience template engines that layer ontop of PHP are only good for the simplest of cases and are easily outgrown.
Secondly the original code is as good as any method. At risk of stating the obvious to make it better abstract it into a function;
function output_block($BACKGROUND, $LINK, $IMAGELINK, $DESCRIPTION, $PRICE)
{
echo "<div id='contentblock' style='background-image:url(images/$BACKGROUND.png);'>
<div id='picture'><a href='$LINK'><img src='$IMAGELINK'/></a></div>
<div id='description'><p>$DESCRIPTION</p></div>
<div id='price'><p class=price>$PRICE</p></div>
</div>";
}
If you want to make it much better then adopt a framework, an entire admin config page is show below. All of the HTML glue is provided by the framework - the following code is real, but really to illustrate how a framework can provide a lot of the grunge work for you.
In the example below if I want to edit a single entity I'd change the TableViewEdit into a FormView and provide an instance of an entity rather than an iterable list.
$entity = new CbfConfig(); // Database entity
$page = new AdminWebPage("Site Configuration"); // Page for output
/*
* build the view
*/
$vil = new ViewItemList();
$col = &$vil->add(new ViewItem("description","Description"));
$col->get_output_transform()->allow_edit(false); // this field cannot be editted
$col = &$vil->add(new ViewItem("value","Value"));
$v1 = new TableViewEdit($entity, $vil,"admin_values"); // present as standard editable table
/*
* output the page
*/
$page->begin();
$iterable_list = CbfConfig::site_begin();
$page->add_body($v1->get_output($iterable_list,'admin_config'));
$page->end();
Id just have all my html code outside of php tags, then whereever I need a variable from php do as follows
<div id="description"><p><?php echo $DESCRIPTION; ?></p></div>
You can loop around non php code too. For example
<?php
for($i = 0; $i < 10; $i++) {
?>
<div id="description"><p><?php echo $i; ?></p></div>
<?php
} //end for loop
?>
Obviously this is just an example.
well if im without a template engine for somereason i usually do something like:
function partial($file, $args = array()) {
extract($args);
ob_start();
include($file);
return ob_get_clean();
}
Really, there are 3 ways of doing this. Use whichever is easiest for you in the context that you are using it in.
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
echo "<div>{$row['fieldName']}</div>";
}
?>
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
echo '<div>'.$row['fieldName'].'</div>';
}
?>
<?php
while(($row=mysql_fetch_assoc($result))!==false)
{
?>
<div><?= $row['fieldName']; ?></div>
<?php
}
?>
I am building a mobile version of my company website, and one thing we are in need of is an RSS feed.
I have the RSS pulling in fine with this code:
<?php
$url = 'http://www.someurl.com/rss/articles';
$feed = simplexml_load_file($url, 'SimpleXMLIterator');
$filtered = new LimitIterator($feed->channel->item, 0, 15);
foreach ($filtered as $item) { ?>
<li data-icon="false">
<h2><?php echo $item->title; ?></h2>
<p class="desc"><?php echo $item->description; ?></p>
<br />
<p class="category"><b><?php echo $item->category; ?></b></p>
<a class="link" href="<?php echo $item->link; ?>">Read More</a>
<br />
<p class="pubDate"><?php echo $item->pubDate; ?></p>
<br />
</li>
<?php } ?>
What I would like to do is utilize either the fopen() or file_get_contents() to handle the clicking of the 'Read More' link and strip all of the contents of the incoming page except for the <article> tag.
I have searched Google the past day, and have not been successful in finding any tutorials on this subject.
EDIT:
I would like to load the stripped HTML contents into their own view within my framework.
SECOND EDIT:
I would just like to share how I solved this problem.
I modified my $item->link; to be passed through the URL as a variable:
Read More
On the article.php page, I collect the variable with a if() statement:
if (isset($_GET['rss_url']) && is_string($_GET['rss_url'])) {
$url = $_GET['rss_url'];
}
Then building on the suggestions of the comments below, I built a way to then collect the incoming URL and strip the necessary tags to then format for my mobile view:
<div id="article">
<?php
$link = file_get_contents($url);
$article = strip_tags($link, '<title><div><article><aside><footer><ul><li><img><h1><h2><span><p><a><blockquote><script>');
echo $article;
?>
</div>
Hopefully this helps anyone else who may encounter this problem :)
I'm not sure if I understand it correctly but are you trying to output the contents on the current page whenever someone clicks the more link?
I would probably use Javascipt to do that, maybe jQuery's .load() function which loads html from another page and allows you to load only specific fragments of a page.. but if you need to use php I would look into Simple HTML DOM Parser
$html = file_get_html($yourUrl);
$article = $html->find('article', 0); // Assuming you only have 1 article/page
echo $article;
The only way I can see is to set up your own separate script to route the links through.
So, instead of echo $item->link use
echo 'LinkProcessor.php?link='.$item->link
Then, setup a script called LinkProcessor.php and use file_get_contents on that page. You can then process the XML to only show the article tag and echo the results:
$article = file_get_contents($_GET['link']);
$xml = new SimpleXMLElement($article);
$articleXml = $xml->xpath('//article');
echo articleXml[0];
Note that the code is untested, but it should be OK.
I am building a picture gallery, that uses this code to display each product I have:
<div class="feature">
<imagetag alt="Image Caption"srcs="">
<div>
<p>
This is some information that can go along with an image.
Anything can be placed here, including images.
</p>
</div>
</div>
I need to create a while loop, that takes all the products in my database, and creates a div of the "feature" class for every instance. I have problems know exactly which symbols need to be escaped and etc. Your help is greatly appreciated.
here is my start:
<?php
($product_set = mysql_fetch_assoc($query)) {
print("<div class="feature"> <imagetage alt="Image Caption" srcs=$product_set[products_image]>"
);}
?>
If you are in a string, every doublequote should be escaped. Because it will close your string.
<?php
($product_set = mysql_fetch_assoc($query))
{
print "<div class=\"feature\"><img alt=\"Image Caption\" src=" . $product_set['products_image'] . ">";
}
?>
Fun thing is, I got a link from someone on stackOverflow about PHP templating. Which was using Smarty. So you don't have to use these print states anymore.
Have you tried:
print(htmlentities($my_html_string))
or htmlspecialchars? htmlentities converts all characters that have one to their HTML escape sequence, while htmlspecialchars converts only those that have meaning in HTML.