I'm pretty new to PHP, got a question, I can't figure out after few research.
Here is my sample code
<?php
$sample = '<div class="sample"><ul><li>123</li><li></li></ul></div>';
$newsample = '<span class="newsample">11</span>';
/* Some code here to put the $newsample variable inside $sample */
?>
My expected output is like below:
<div class="sample">
<li>123</li>
<li><span class="newsample">11</span></li>
</div>
Is there anyway we can do that?
Related
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>
I have a complex HTML tag, with many attributes and it appears in very different parts of the code.
Example:
<div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" >
<some complex html code ... >
</div>
And I do not want to repeat this <div></div> with all its attributes in different parts of the code as it changes quite often during development.
If I create a function like this (example in PHP):
function myDivStart() { ?>
<div class="blabla" data-attribute="blablabla" data-another-attribute="blabla">
<?php }
then my resulting code would look like
<?php myDivStart(); ?>
<some html code ... >
</div>
and the finishing </div> would look kind of out-of-place, since there is no visual starting <div>. My text editor would also not parse this correctly and syntax highlighting is messed up.
Then, if I create another function for the closing </div>, it would be a very silly function indeed:
function myDivEnd() { ?>
</div>
<?php }
and turn the original code into
<?php myDivStart(); ?>
<some html code ... >
<?php myDivEnd(); ?>
This would solve the syntax highlighting problem, but it still feels very unclean to have such a silly function to close.
UPDATE: Storing the HTML code in a variable and passing that to a function would not really solve the problem neither, as the HTML inside a variable would not be parsed correctly with syntax highlighting.
$myHTML = 'A very long and complex piece of html';
<?php myDiv($myHTML); ?>
My text editor would not have syntax highlighting there.
And doing the following would also make the code disorderly, as the $myHTML code comes before the <div> and actually, logically belongs after it.
$myHTML = ?>
A very long and complex piece of html
<?php ;
myDiv($myHTML);
Is there any pattern that would solve for this?
If it's always the same tag you can use a variable or a constant instead of a function.
E.g.
$openTag = "<div class=\"blabla\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >";
$closeTag = "</div>";
If you have varying parts of that tag then you can instead indeed make a function, e.g.:
function openingDiv($class) {
return "<div class=\"$class\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >"
}
function closingDiv() {
return "</div>";
}
You can also make it a bit more sophisticated:
function wrapContentInDiv($content) {
return "<div class=\"$class\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >$content</div>";
}
Example uses:
<?php
$openTag = "<div class=\"blabla\" data-test=\"blablabla\" ... data-another-attribute=\"blabla\" >";
$closeTag = "</div>";
?>
<leading html>
....
<?php echo $openTag ?>
<some html here>
<?php echo $closeTag ?>
...
<?php echo $openTag ?>
<some other html here>
<?php echo $closeTag ?>
<trailing html>
You can take this one step further and define your code in a separate php file:
e.g. config.php
Then you can:
<?php
require_once("config.php")
?>
...
Update:
You could also use a template e.g. file complexDiv.php
<div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" >
Use this as below:
<leading html>
....
<?php //Set any parameters that complexDiv.php needs here
include 'complexDiv.php'
?>
<some html here>
</div>
...
<?php include 'complexDiv.php' ?>
<some other html here>
</div>
<trailing html>
I suspect that before long you'll realise that its worth switching to a template engine like smarty of blade.
It depends on what the some HTML code is but you could do something like this pseudocode
$some_html=''; //your html code goes here as a string
myDiv($some_html);
function myDiv( $arg ){
echo <div class="blabla" data-attribute="blablabla" data-another-attribute="blabla">
echo $arg;
echo </div>
}
You can first prepare the HTML on a different file and include that file on the function where the div tags are waiting for them to wrap that content of yours. Hope it helps.
function wrapperDiv() {
$html = '';
$html .= '<div class="blabla" data-test="blablabla" ... data-another-attribute="blabla" >';
$html .= include_once 'body.php';
$html .= '</div>';
return $html;
}
wrapperDiv();
I hope its not duplicate or already been answered because I cant find nothing similar on SO.
I have included file: include 'data/news.php';
<?php
$news = '
<div class="news_title">News Title</div>
<div class="news_date">Newsdate</div>
<div class="news_content">News content</div>
';
echo $news;
?>
In index file I try to show $news like this:
<div class="rightbox"><div class="h1title">Novice</div>
<?php $news ?>
</div>
Class "rightbox" is floated to the right side, but my $news is displayed right after menu content, its not in < div class =" rightbox " > "here" < /div > as I thought it should be (it makes no sense -> it should be in rightbox div but its not ??
Here's a screenshot of firebug:
http://i43.tinypic.com/kz505.png
I cant find any explanation on this so any suggestions would be welcome.
echo <-- you need to echo the variable.
Simply writing the variable name in the php does nothing. You need to print the contents of the variable to the page.
Two possible ways of doing this are:
1.echo
echo $news;
2. print
print $news;
They both to the same thing.
So I'm wanting to make a way to display the 2nd newest row from my database. So my example (To help better explain it) If i have 10 rows. I want to display only the second newest one. Not the newest one but the one right after it. Or the maybe even the third one. I have my working code below and i see the for each loop. But I'm not sure how to only display the one I'm wanting it to display. I also don't think how i have it set up is the most efficient way of acomplishing this.
I am using concrete5 for this site and the main idea is for composer so i can post a new post and the pull a recent news feed but showing the second post.
Here is my current code: (This shows the first post)
<?php
defined('C5_EXECUTE') or die("Access Denied.");
?>
<div id="blog-index">
<?php
$isFirst = true; //So first item in list can have a different css class (e.g. no top border)
$excerptBlocks = ($controller->truncateSummaries ? 1 : null); //1 is the number of blocks to include in the excerpt
$truncateChars = ($controller->truncateSummaries ? $controller->truncateChars : 255);
$imgHelper = Loader::Helper('image');
foreach ($cArray as $cobj):
$title = $cobj->getCollectionName();
$date = $cobj->getCollectionDatePublic(DATE_APP_GENERIC_MDY_FULL);
$author = $cobj->getVersionObject()->getVersionAuthorUserName();
$link = $nh->getLinkToCollection($cobj);
$firstClass = $isFirst ? 'first-entry' : '';
$entryController = Loader::controller($cobj);
if(method_exists($entryController,'getCommentCountString')) {
$comments = $entryController->getCommentCountString('%s '.t('Comment'), '%s '.t('Comments'));
}
$isFirst = false;
?>
<div class="entry">
<div class="title">
<h3>
<?php echo $title; ?>
</h3>
<h6 class="post-date">
<?php
echo t('Posted by %s on %s',$author,$date);
?>
</h6>
</div>
<div class="excerpt">
<?php
$a = new Area('Main');
$a->disableControls();
if($truncateChars) {
$th = Loader::helper('text');
ob_start();
$a->display($cobj);
$excerpt = ob_get_clean();
echo $th->entities($th->shorten($excerpt,$truncateChars));
} else {
$a->display($cobj);
}
?>
</div>
<div class="ccm-spacer"></div>
<br />
<div class="meta">
<?php echo $comments; ?> <?php echo t('Read the full post'); ?> <i class="icon-chevron-right"></i>
</div>
</div>
<hr class="blog-entry-divider"/>
<?php endforeach; ?>
</div>
To build upon what the others have written as comments:
What you've pasted is a concrete5 view. You'll notice there's no db querying or PageList building in there. For that, you need to look in the controller. (This looks like a page list block view, so the controller will be in / concrete / core / controllers / blocks / page_list.php (on c5.6+).
The concrete5 api code to do what the others have suggested (let mysql handle the skipping) is done within the ->get() call. So, on about line 135:
$pl->get(1, 1);
Remember not to modify the files directly, but to override them the c5 way. There are plenty of tutorials on this on the c5 website.
I currently have the following code coming from a database table:
<h1 class="widgetHeader">My Friends</h1>
<div class="widgetRepeater">
<p class="widgetHeader">Random Selection</p>
<?php
$friends = $user->getFriends();
?>
<p class="widgetContent">
<?php
for ($i=0; $i<count($friends);$i++) {
$friend = $friends[$i];
?>
<span class="friendImage" style="text-align:center;">
<?php print $friend->username; ?>
</span>
<?php
}
?>
</p>
</div>
Now, ive tried using the eval function in php but i get a parse error unexpected '<'. I've also tried using the output buffer method (ob_start) without success too. Any ideas as to how i can get this code to evaluate without giving me an error?
note: the database code is stored in a variable called $row['code'].
The PHP eval function expects PHP code to execute as it's parameter, not HTML. Try enclosing your DB values with PHP close and open tags:
eval('?>' . $row['code'] . '<?php');
eval = evil!
Especially if the eval'd code comes from a db... one mysql injection = full php execution = full control.
Rather use some placeholders and replace them (like any other good templating system does).
You could store this in your database:
<h1 class="widgetHeader">My Friends</h1>
<div class="widgetRepeater">
<p class="widgetHeader">Random Selection</p>
{%friendstemplate%}
</div>
Then str_replace the placeholders with the content they should have. In your example i would also add a subtemplate per friend like this:
<span class="friendImage" style="text-align:center;">
{%username%}
</span>
... which you could loop and insert into {%friendstemplate%}.
You cant use eval on markup code. Either save the code to a temporary file so that you can include it, or rewrite the code so that it's not markup, something like:
print "<h1 class=\"widgetHeader\">My Friends</h1>";
print "<div class=\"widgetRepeater\">";
print "<p class=\"widgetHeader\">Random Selection</p>";
$friends = $user->getFriends();
print "<p class=\"widgetContent\">";
for ($i=0; $i<count($friends);$i++) {
$friend = $friends[$i];
print "<span class=\"friendImage\" style=\"text-align:center;\">";
print $friend->username;
print "</span>";
}
print "</p>";
print "</div>";