Line Break in PHP for-loop - php

There have been a bunch of questions like this already, but none of the answers seem to help me. I would like to have a line-break after each output from a loop. I am using double-quoted strings, like I read here, as well as using HTML (because I want the browser to recognize the line-breaks too) as I read here.
It does create a line-break, however only below the complete output.
I cannot manage to create a line-break between the outputs of the loop. Basically I get a block of text and then a linebreak.
Here is the loop I am using:
<?php
include_once('simple_html_dom.php');
$target_url = "http://www.buzzfeed.com/trending?country=en-us";
$html = new simple_html_dom();
$html->load_file($target_url);
$posts = $html->find('ul[class=list--numbered trending-posts trending-posts- now]');
$limit = 10;
$limit = count($posts) < $limit ? count($posts) : $limit;
for($i=0; $i < $limit; $i++){
$post = $posts[$i];
$post->find('div[class=trending-post-text]',0)->outertext = "";
echo strip_tags($post, '<p><a>') . "<br/>\n";
}
I've also tried "\r\n" and a bunch of variations, as well as the nl2br() function. I believe the PHP_EOL command is meant only for the command line, from what I've researched.
I'm an absolute beginner with PHP, so I am probably missing something simple, but I can't figure it out.
EDIT:
Here is what it prints:
http://globalsocialnews.com/crawler/test8.php
I also included the complete code in case that helps.

You can do line break using css implementation ...
like:
.rcorners1 a {
display: block;
margin-bottom: 10px;//for show extra margin between each line...
}
Edit: Use margin css attribute for extra margin...
please try implementing this...

Better Use
echo "</br>";

Related

PHP getElementsByTagName('*') avoid duplicate nodes | "In Text ads" by separating content nodes

the source of this problem is because I'm running ads on my website, my content is mainly HTML stored in a database, so I decided to place "In-Text Ads", ads that are not in a fixed zone.
My solution was to explode the content by paragraphs and place the text ad in the middle of the p tags, which worked pretty cool since I use CKEditor to generate the content, I thought images, blockquotes, and other tags would be nested inside p tags (fool me) I realize now that images and blockquotes disappeared from my posts, what did I do next? I changed my code to explode using * instead of exploding by p tag, I sang victory too soon, because now I get a lot of duplicate content, for example, if I have one image now I get the same image 4 times as well as all other tags, I´m not sure about the source of this duplicates but I think It has something to do with nested HTML, I looked for a solution for hours and now I'm here asking to see whether somebody can help me solve this headache
Here is my code:
//In a helper file
function splitByHTMLTagName(string $string, string $tagName = 'p')
{
$text = <<<TEXT
$string
TEXT;
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$nodes = [];
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $text);
foreach ($dom->getElementsByTagName($tagName) as $node) {
array_push($nodes, $dom->saveHTML($node));
}
libxml_clear_errors();
return $nodes;
}
//In my view
$text = nl2br($database['content']);
$nodes = splitByHTMLTagName($text, '*');
//Using var_dump($nodes); here shows the duplicates are here already.
$nodes_count = count($nodes);
$show_ad_at = -1;
$was_added = false;
if($nodes_count % 2 == 0 ){
$show_ad_at = $nodes_count /2;
}else if ($nodes_count == 1 || $nodes_count < 3){
$show_ad_at = -1; //add later
}else if ($nodes_count > 3 && $nodes_count % 2 != 0){
$show_ad_at = ceil($nodes_count/2);
}
for($i = 0; $i<count($nodes); $i++){
if(!$was_added && $i == $show_ad_at){
$was_added = true;
?>
<div>
<script></script><!--This script is provided to me, it adds the ad where it is placed, I don't show the full script, It has nothing to do with the duplicates problem-->
</div>
<?php
}
echo $nodes[$i]; //print the node that comes from $nodes array where the duplicates already exist
}
if(!$was_added){
$was_added = true;
?>
<div>
<script></script><!--This script is provided to me, it adds the ad where it is placed, I don't show the full script, It has nothing to do with the duplicates problem-->
</div>
<?php
}
What can I do?
Thanks in advance.
Postdata #1: I use codeigniter as PHP Framework
Postdata #2: My ads provider does not implement "In-Text ads" as a feature like google does.
It seems you are printing the "ads block" inside if statement.
If I don't misunderstood your code is like
foreach ... {
if (strpos($html_line, "In-Text Ads") !== FALSE) {
print($ads_html);
}
I think, you should use str_replace() instead of print() like functions, if you are using something like print() when you outputting the value...

Could not continue the converting process from HTML element to DOM due to messy input data

I need your help...
I have a function to manipulate the HTML element to change the image url using DOM parse. My function was working properly. Here's my code:
//Update image src with new src
function upd_img_src_in_html($html_src='', $new_src='')
{
if($html_src == '' || $new_src == ''):
return '';
endif;
$xml = new DOMDocument();
$xml->loadHTML($html_src, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$imgNodes = $xml->getElementsByTagName('img');
for ($i = $imgNodes->length - 1; $i >= 0; $i--) {
$imgNode = $imgNodes->item($i);
$image_file_names = pathinfo($imgNode->getAttribute('src'), PATHINFO_BASENAME);
if(!empty($image_file_names)):
$imgNode->setAttribute('src', $new_src.$image_file_names);
$imgNode->setAttribute('style', 'max-width:90%; margin-left:auto; margin-right:auto;');
endif;
}
return html_entity_decode($xml->saveHTML());
}
However a lot of problems come after I made this function.
No 1: result_box already defined in Entity line 1
No. 2: unexpected line tag..
I cannot control at all the input from $html_src='' to make it run smoothly. I've tried some effort on dealing with the problem 1 but still not success. For example I used libxml_use_internal_errors() but still got the error.
The second problem I can not overcome it. Is it any easiest way to handle only to change image src instead of using DOMDocument()?
The answers from expert really needed here. Please give me some advice on how to deal with these problems.
Thank you..
One way to deal with messy HTML and DOMDocument is to use the PHP tidy extension first, which will correct all the errors that are in it.

Removing last comma from out in PHP that is going into a javascript image pre-load script

Hi I have a javascript pre-load script that incorporates a php command to pre-load uploaded images for a future onClick action. Anyway I am having trouble removing the LAST comma from the last image the pre-load script pulls from.
Here is the script:
<div style="display:hidden">
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
<?php
for ($i = 0; $i < 6; $i++) {
if (!empty($imgs[$i])) {
echo "'http://www.samplegallery.com/upload/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=500',";
}
}
?>
)
//--><!]]>
</script>
</div>
Anyway, I need to find out how to remove the last comma from the last image that is uploaded. Not sure how to do this. Please help me! BTW... the images don't have an extension since they are linking to a php image script that resizes them and places them into a watermark. Hope you guys can help me figure!
Think the other way! the comma could be at the start and then you remove it from the first one :)
if (!empty($imgs[$i])) {
$comma = $i == 0? '' : ',';
echo $comma."'http://www.samplegallery.com/upload/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=500'";
}
This way doesn't matter if $i is equal to 5, 8 or 139871!
The easiest way to do it is using the php build in implode() function
<?php echo implode(',', $imgs); ?>
And if you want just the first 6 images, you can make an array like so
$imgs = array_slice($imgs, 0, 6);
So the whole thing must look like that:
preload(
<?php
$imgs = array_slice($imgs, 0, 6);
echo implode(',', $imgs);
?>
)
to remove the last comma from a string, just use this:
$string = rtrim($string, ",");
May I suggest a slightly different approach to your problem? Whenever you want to pass data to JavaScript, JSON is probably the thing you want to generate. json_encode() helps you with that. Your script could look like:
var urls = <?php echo json_encode(array_values($imgs)); ?>;
var images = [];
function preload(urls) {
for (var i = 0; i < urls.length; i++) {
var url = 'http://www.samplegallery.com/upload/image.php?img_source_url='
+ encodeURIComponent(urls[i])
+ '&img_resize_to=500';
images[i] = new Image();
images[i].src = url;
}
}
preload(urls);
please note that I've taken the liberty of adding missing semicolons and var declarations to keep your variables local. I have added the array_values() call to make sure you're passing a numerically indexed array, rather than an associative array that would have resulted in an object literal { ... } rather than an array literl [ ... ].
I have also moved the URL building to JavaScript, as I didn't see a reason to keep it in PHP. If you need this to be in PHP and want to avoid the "manual" loop, look into array_map().
Please also note that I'm running your URL fragment through encodeURIComponent() to properly escape whatever it is you're passing in.
A note on security: should your script at /upload/image.php accept arbitrary URLs (and or "local file resources"), consider white-listing the allowed domains and paths.
You could use a foreach...
<?PHP
if ($count = count($imgs)) {
foreach ($imgs as $key=>$img) {
echo "http://www.samplegallery.com/upload/image.php?img_source_url="
. $img . "&img_resize_to=500";
if ($key < $count-1) echo ",";
}
}
?>

Retrieve first 10 comments from .html file

I was goog for hours and just cannot find an answer. Please suggest:
Having a .html file that contains only user comments in paragraphs like:
<p>12/02/2012 4:32pm Mark</p>
<p>Hi! it's a nice demo! Really thankful</p>
<hr>
<p>11/02/2012 11:03am Miron</p>
<p>How to change the font size from CFD again?</p>
<hr>
<!-- AND LOADS OF OTHER <P><P> COMMENTS DELIMITED BY <HR> ... -->
There's 1000's of comments structured like this,
I'd like to grab somehow the newest 10 (not by date, just the first 'ten' comments). And I don't know how.
I know I can use jQuery's .load('comments.html') and than remove all the elements but the first 10 comments, or even include the whole file with PHP and than do the .hide() with jQuery... but it's a good idea to load the whole file for just 10 comments?
How to split that file and get inside an <div id="latest_10_comments"></div> the first 10 comments from the comments.html file?
I know you wanted a JavaScript solution but you could do this in PHP by using the explode function.
Something like this:
$comments = explode("<hr>", file_get_contents("/comments.html"));
for($i = 0; $i < 10; $i++) {
print($comments[$i]);
}
This creates an array called $comments which is each comment in comments.html separated by a
<hr>
tag.
First, I'd suggest reconsidering your approach to this problem entirely. Why are you storing everything an in HTML file this way? You should either store it as an XML file or store it in your database if you want to dynamically load certain comments on demand.
However, to answer your question you're going to need to use an X/HTML parser like PHP's DomDocument if you want to do this in PHP. Here's a working example...
EDIT (changed to reflect the OP's desired behavior):
$dom = new DomDocument;
$dom->loadHTMLFile("comments.html");
// Get all the P tag elements in the DOM
$comments = $dom->getElementsByTagName('p');
// Get only the first 10
$amount = 10; // number of comments you want
foreach ($comments as $num => $comment_nodes) {
if ($num + 1 > $amount)
break;
echo $comment_nodes->nodeValue, PHP_EOL;
}
Solution 1. You can use a RegEx pattern to match 2 p tags followed by hr and repeat the pattern for 10 times.
Solution 2.
Idea from other answer(CHRIS), but as that has error in PHP, I am suggesting this.
$comments = explode("<hr>", file_get_contents("/comments.html"));
for($i = 0; $i < 10; $i++) {
print($comments[$i]);
}
$("<p>").each(function(index, value)
{
//Do what you want here
}
This will cycle through all your <p>. If you know the order of the elements then you can do what you want with them based on index.

php simplexml_load_file with a dash ( - )

Hi I'm struggling to get data from an xml file in php...
the xml file is here: http://musicbrainz.org/ws/2/artist/8bfac288-ccc5-448d-9573-c33ea2aa5c30?inc=release-groups
and so far after loading it into simplexml_load_file as $xml
I want to do something like this:
<?php
$url = "http://musicbrainz.org/ws/2/artist/8bfac288-ccc5-448d-9573-c33ea2aa5c30?inc=release-groups";
$xml = simplexml_load_file($url);
$releasegrouplist = "release-group-list";
$releasegroup = "release-group";
$i = "0";
for ($i = 0; $i <= 30; $i++)
{
echo "release: " . $xml->artist->$releasegrouplist->$releasegroup[$i]->title;}
The problem arises when I try to use it in a for loop with an $i variable as shown above.
Any tips or easier ways to do this?
Thanks everyone
Try this syntax instead. This script works for me with the change below (PHP 5.3.6).
echo "release: " . $xml->artist->{'release-group-list'}->{'release-group'}[$i]->title;
Source
You haven't actually told us what the problem is, but I'm guessing it's that you haven't read the SimpleXML section in the PHP manual, where it says
Accessing elements within an XML document that contain characters not
permitted under PHP's naming convention (e.g. the hyphen) can be
accomplished by encapsulating the element name within braces and the
apostrophe.

Categories