Parsing content only storing one result [duplicate] - php

This question already has answers here:
PHP - For loop only returns last variable in array
(2 answers)
Closed 1 year ago.
I am having some issues getting my extremely messy code to submit data properly. Currently I am scraping a website which harbors many images and trying to collect them all and store them accordingly via my WordPress the_content selection.
Here's what I've got going so far, this is returning the images almost without any issues when I load it via a standard loop.
foreach ($html2->find('.entry-content img') as $image) {
$imageurl = $image->src;
$new = '<img src="' . $imageurl . '" style="height: auto; width: 100%;margin-bottom: 3px;">';
print $thecontent = htmlspecialchars($new); print '<br>';
} foreach ($html2->find('iframe') as $video) {
$videourl = $video->src;;
$new = '<iframe src="' . $videourl . '" scrolling="no" frameborder="0" width="100%" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>';
print $thecontent = htmlspecialchars($new); print '<br>';
}
The above code will return something that looks like this containing 1 - how ever many images + videos we're trying to gather.
<img src="https://www.example.com/some-image-path-here.jpg" style="height: auto; width: 100%;margin-bottom: 3px;">
<img src="https://www.example.com/some-image-path-here.jpg" style="height: auto; width: 100%;margin-bottom: 3px;">
<img src="https://www.example.com/some-image-path-here.jpg" style="height: auto; width: 100%;margin-bottom: 3px;">
<img src="https://www.example.com/some-image-path-here.jpg" style="height: auto; width: 100%;margin-bottom: 3px;">
Now here's what I am using to try and upload the content to my WordPress site (everything except $content appears to be working properly.
$content = $thecontent;
$my_post = array(
'post_title' => wp_strip_all_tags( trim( $title ) ),
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 2,
'post_category' => array(2),
'post_date' => date('Y-m-d H:i:s')
);
$post_id = wp_insert_post( $my_post );
remove_filter('content_save_pre', 'wp_filter_post_kses');
remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
The above code returns the following within my WordPress the_content portion, which is the first image only, how can I make this work?
<img src="https://www.example.com/some-image-path-here.jpg" style="height: auto; width: 100%;margin-bottom: 3px;">
Note: The portion which is storing the WordPress data is being loaded inside of our initial parse loop, but outside of the loop which is collecting the images + videos.

Each time round the loop your just collecting one piece of information and setting $thecontent to that field and printing it out. You need to add these to together to get a string containing all of the content...
$thecontent = '';
foreach ($html2->find('.entry-content img') as $image) {
$imageurl = $image->src;
$new = '<img src="' . $imageurl . '" style="height: auto; width: 100%;margin-bottom: 3px;">';
$thecontent .= htmlspecialchars($new).'<br>';
}
foreach ($html2->find('iframe') as $video) {
$videourl = $video->src;;
$new = '<iframe src="' . $videourl . '" scrolling="no" frameborder="0" width="100%" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>';
$thecontent .= htmlspecialchars($new).'<br>';
}
print $thecontent;
Note where in each loop I use .= to append the new content to the end of the list. The final content is printed out and should be used

Related

Make each post on its own unique div

A couple of months ago, I asked a similar question like this and the answer that where given worked for me. I now have another change I would like to add to my page. I would like that each post I create has its own unique div. My page currently looks like this:
the previous question helped me break the div each 3 post, so what I tried was within the if statement that creates a new dive each 3 div was to add another if which would break each 1 div so that each post has its own div and it still breaks to a new div section each 3, maybe I just complicated everything with my description, but I want to get something like:
Here is my code
CSS:
.column {
display: inline-flex;
border: 5px black;
border-style: solid;
padding: 10px;
background: #ffa500;
}
PHP:
else {
$break = 0;
$nRows = $connection->prepare("SELECT post_id, post_title,
post_author, post_file, post_time
FROM posts
ORDER BY post_id DESC");
$nRows->execute();
if($nRows->rowCount() > 0) {
while ($row = $nRows->fetch()) {
$post_title = str_replace('_', ' ', $row['post_title']);
$post_author = $ed->encrypt_decrypt('decrypt',$row['post_author']);
$post_file = $row['post_file'];
$post_date = $row['post_time'];
// Create a new div each 3 columns
if ($break % 3 === 0) {
echo '<br><div class="column"><br>';
}
$break++;
?>
<!-- Blog Content BEGIN Display-->
<div class="box"><?php
// Display the content
$file_parts = pathinfo($post_file);
if(isset($file_parts['extension'])) {
switch ($file_parts['extension']) {
case "jpg":
if(!empty($post_file)) { ?>
<img src="post/postFiles/<?php echo $post_file;?>"><?php
}
break;
case "mp4":?>
<div class="thumbnail">
<video preload="auto" loop muted>
<source src="post/postFiles/<?php echo $post_file;?>">
</video>
</div>
<!-- Preview video on hover -->
<script>
$(document).ready(function () {
$(".thumbnail").hover(function () {
$(this).children("video")[0].play();
}, function () {
var el = $(this).children("video")[0];
el.pause();
el.currentTime = 0;
});
});
</script><?php
break;
case "": // Handle file extension for files ending in '.'
case NULL: // Handle no file extension
break;
}
}
// Title URL Variable
$urlFetchPostId = '<h2><a href="post/postFetch/fetchByTitle/fetchByPT.php?post_id=';
$urlFetchPostTitle = '&post_title=';
$urlFetchPostAuthor = '&post_author=';
echo $urlFetchPostId . $row['post_id'] . $urlFetchPostAuthor. $row['post_author']. $urlFetchPostTitle . $row['post_title'] . '"' . 'class="link-post-title" style="font-family: Arial">' . " ". $post_title . '</a></h2>';
// Author/User URL Variable
$urlFetchPostUser = '<a href="post/postFetch/fetchByAuthor/fetchByPA.php?post_author=';
echo $urlFetchPostUser . $row['post_author'] . '"' . 'class="link-post-author" style="font-family: Arial">' . " ". strtoupper($post_author) . '</a>';
// Posted Date
echo '<br><p style="font-family: Arial">Posted on ' . $post_date . '</p>';
?>
</div><?php
if ($break % 3 === 0) {
echo '<br></div><br>';
}?>
<!-- Blog Content END Display --><?php
}
} else { ?>
<p style="color: darkgoldenrod" class="mssgAlign"><u>NO RECORDS</u></p><?php
}
$nRows = null;
}
Any help, tip or improvement suggestion is welcomed
You want to use margins. Margins specify a buffer around the outside of your container. As opposed to padding, which specifies buffer inside the container. Add this to your css
.column {
display: inline-flex;
border: 5px black;
border-style: solid;
padding: 10px;
background: #ffa500;
margin-left: 20px;
margin-right: 20px;
}

increment id for dynamically generated div

I want to dynamically generate video player container divs that will have a unique id. The elements are generated through Visual Composer in WordPress and the final html should look something like this:
<div style="width: 100%; display: inline-block; position: relative;">
<div style="margin-top: '. $custom_margin .'"></div>
<div id="player_1" style="position:absolute;top:0;left:0;right:0;bottom:0"></div>
</div>
<div style="width: 100%; display: inline-block; position: relative;">
<div style="margin-top: '. $custom_margin .'"></div>
<div id="player_2" style="position:absolute;top:0;left:0;right:0;bottom:0"></div>
</div>
<div style="width: 100%; display: inline-block; position: relative;">
<div style="margin-top: '. $custom_margin .'"></div>
<div id="player_3" style="position:absolute;top:0;left:0;right:0;bottom:0"></div>
</div>
The user should be able to add as many div elements with unique ids as he likes. This is how my php looks right now:
EDIT: The function is called for every single video container
public function vc_custvideo_html($atts){
extract(
shortcode_atts(
array(
'custom_width' => '',
'custom_height' => '',
),
$atts
)
);
$percent = $custom_height / $custom_width;
$custom_margin = number_format( $percent * 100, 2 ) . '%';
$html = '';
$html.= '<div style="width: 100%; display: inline-block; position: relative;">';
$html.= '<div style="margin-top: '. $custom_margin .'"></div>';
$html.= '<div id="player_" style="position:absolute;top:0;left:0;right:0;bottom:0"></div>';
$html.= '</div>';
return $html;
}
I can understand that i have to use a foreach loop to generate the unique ids but i'm really new at php and I need help.
Something like that
$i = 0;
foreach ($playerInstance as $k => $currPlayer {
vc_custvideo_html($currPlayer, $i)
$i++;
}
public function vc_custvideo_html($atts, $index){
extract(
shortcode_atts(
array(
'custom_width' => '',
'custom_height' => '',
),
$atts
)
);
$percent = $custom_height / $custom_width;
$custom_margin = number_format( $percent * 100, 2 ) . '%';
$html = '';
$html.= '<div style="width: 100%; display: inline-block; position: relative;">';
$html.= '<div style="margin-top: '. $custom_margin .'"></div>';
$html.= '<div id="player_'.$index.'" style="position:absolute;top:0;left:0;right:0;bottom:0"></div>';
$html.= '</div>';
return $html;
}
Or with a for loop maybe
Assuming the function is called once per Video, use an outer foreach and a counter:
$counter=1;
foreach($arrayOfVideos as $video){
$this->vc_custvideo_html($video, $counter);
$counter++;
}
And inside your function, just use the $counter variable:
// [...]
$html.= '<div style="margin-top: '. $custom_margin .'"></div>';
$html.= '<div id="player_"' . $counter . ' style="position:absolute;top:0;left:0;right:0;bottom:0"></div>';
$html.= '</div>';

Custom HTML for WordPress Image Gallerys, only outputs half the function

I took the following code from an example and adjusted it so a standard gallery in wordpress would output as a Flexslider and Carousel. I can output one of them just fine, but I added additional *outputs for a Carousel as well, and now only the Carousel prints out. Any help on how I can get the whole thing to output would be appreciated
add_filter('post_gallery', 'my_post_gallery', 10, 2);
function my_post_gallery($output, $attr) {
global $post;
if (isset($attr['orderby'])) {
$attr['orderby'] = sanitize_sql_orderby($attr['orderby']);
if (!$attr['orderby'])
unset($attr['orderby']);
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ('RAND' == $order) $orderby = 'none';
if (!empty($include)) {
$include = preg_replace('/[^0-9,]+/', '', $include);
$_attachments = get_posts(array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby));
$attachments = array();
foreach ($_attachments as $key => $val) {
$attachments[$val->ID] = $_attachments[$key];
}
}
if (empty($attachments)) return '';
// Here's your actual output, you may customize it to your need
$output = "<div class=\"wordpress-gallery\">\n";
$output = "<div id=\"sliding\" class=\"flexslider flexslider--post-content\">\n";
//$output .= "<div class=\"preloader\"></div>\n";
$output .= "<ul class=\"slides flexslider__slides\">\n";
// Now you loop through each attachment
foreach ($attachments as $id => $attachment) {
// Fetch the thumbnail (or full image, it's up to you)
// $img = wp_get_attachment_image_src($id, 'medium');
// $imgThumbnail = wp_get_attachment_image_src($id, 'thumbnail');
$img = wp_get_attachment_image_src($id, 'full');
$output .= "<li class=\"slide flexslider__slide cover\">\n";
$output .= "<img src=\"{$img[0]}\" width=\"{$img[1]}\" height=\"{$img[2]}\" alt=\"\" />\n";
$output .= "</li>\n";
}
$output .= "</ul>\n";
$output .= "</div>\n";
$output = "<div id=\"carousel\" class=\"flexslider flexslider--post-content-carousel\">\n";
$output .= "<ul class=\"slides flexslider__slides\">\n";
foreach ($attachments as $id => $attachment) {
$imgThumbnail = wp_get_attachment_image_src($id, 'thumbnail');
$output .= "<li >\n";
$output .= "<img src=\"{$imgThumbnail[0]}\" alt=\"\" />\n";
$output .= "</li>\n";
}
$output .= "</ul>\n";
$output .= "</div>\n";
$output .= "</div>\n";
return $output;
}
the html that gets outputed so far (it doesn't output the #sliding div, only the #carousel):
<div id="carousel" class="flexslider flexslider--post-content-carousel">
<div class="flex-viewport" style="overflow: hidden; position: relative;">
<ul class="slides flexslider__slides" style="width: 1400%; transition-duration: 0s; transform: translate3d(0px, 0px, 0px);">
<li class="flex-active-slide" style="width: 210px; float: left; display: block;">
<img src="//localhost:3002/test-site/wp-content/uploads/2016/01/test-image-300x300.jpg" alt="" draggable="false">
</li>
<li style="width: 210px; float: left; display: block;">
<img src="//localhost:3002/test-site/wp-content/uploads/2016/01/test-image-1-300x300.jpg" alt="" draggable="false">
</li>
<li style="width: 210px; float: left; display: block;">
<img src="//localhost:3002/test-site/wp-content/uploads/2016/01/test-image-2-300x300.jpg" alt="" draggable="false">
</li>
<li style="width: 210px; float: left; display: block;">
<img src="//localhost:3002/test-site/wp-content/uploads/2016/01/test-image-3-300x300.jpg" alt="" draggable="false">
</li>
<li style="width: 210px; float: left; display: block;">
<img src="//localhost:3002/test-site/wp-content/uploads/2016/01/test-image-4-300x300.jpg" alt="" draggable="false">
</li>
<li style="width: 210px; float: left; display: block;">
<img src="//localhost:3002/test-site/wp-content/uploads/2016/01/test-image-5-300x300.jpg" alt="" draggable="false">
</li>
<li style="width: 210px; float: left; display: block;">
<img src="//localhost:3002/test-site/wp-content/uploads/2016/01/test-image-6-300x300.jpg" alt="" draggable="false">
</li>
</ul>
</div>
<ul class="flex-direction-nav">
<li class="flex-nav-prev"><a class="flex-prev flex-disabled" href="#" tabindex="-1">Previous</a></li>
<li class="flex-nav-next"><a class="flex-next" href="#">Next</a></li>
</ul>
</div>
You have a few errors, that I can see.
// Here's your actual output, you may customize it to your need
$output = "<div class=\"wordpress-gallery\">\n";
$output = "<div id=\"sliding\" class=\"flexslider flexslider--post-content\">\n";
If you wish to append data, you need to put a period . before your equals = like this .= on the second $output assignment. Anytime you are appending but not putting .= after the variable name, you are basically reassigning it a new value instead of adding to it.
Also change this line:
$output = "<div id=\"carousel\" class=\"flexslider flexslider--post-content-carousel\">\n";
to:
$output .= "<div id=\"carousel\" class=\"flexslider flexslider--post-content-carousel\">\n";
The problem lies in the fact that you were basically resetting the variable with a new output instead of appending the data to it.
Hope this helps you.
Be sure to go through your code and double check variable assignments to make sure you are appending rather than resetting.
You have two errors in your code, that lies in following lines:
$output = "<div id=\"sliding\" class=\"flexslider flexslider--post-content\">\n";
[...]
$output = "<div id=\"carousel\" class=\"flexslider flexslider--post-content-carousel\">\n";
You are resetting $output variable two times, thus what was written to it before is lost, so you should replace them with:
$output .= "<div id=\"sliding\" class=\"flexslider flexslider--post-content\">\n";
[...]
$output .= "<div id=\"carousel\" class=\"flexslider flexslider--post-content-carousel\">\n";

Php str_replace with &quote not working

my code is:
$retval = preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $content, $image);
$imgreal = str_replace(""", "\"", $image['src']);
if ($retval=="0") $imgthumb = ""; else $imgthumb = "<img align='left' src='".$imgreal."' width=100 />";
I need to extract an img from a string, but this gave me all time:
"http://www.racingzone.hu/pictures/news/mid/simroc-3---nyolc-uj-auto_2012-09-21-1348222495.jpg" alt="" width="490" height="214
How can I change those &quotes to normal chars "?
I tried htmlspecialchars_decode but that not worked to.
edit: the string coming from az sql table.
original string from mysql:
<p><img style="float: left; margin: 3px;" src="http://www.racingzone.hu/pictures/news/mid/simroc-3---nyolc-uj-auto_2012-09-21-1348222495.jpg" alt="" width="490" height="214" /></p>
<p>todik púőúőóüsztotodik púőúőóüsztotodik
string created by TinyMCE
coding in the table: latin2_hungarian_ci
Why does everybody always want to do these kind of things with a regex?
Simply:
$data='<p><img style="float: left; margin: 3px;" src="http://www.racingzone.hu/pictures/news/mid/simroc-3---nyolc-uj-auto_2012-09-21-1348222495.jpg" alt="" width="490" height="214" /></p>
<p>todik púőúőóüsztotodik púőúőóüsztotodik';
$a=explode('src="',$data);
if(count($a)<2)
{
echo 'no image';
die;
}
$p=strpos($a[1],'"',0);
if($p===false){
echo 'no quote found';
die;
}
$url=substr($a[1],0,$p);
echo $url;
Output:
http://www.racingzone.hu/pictures/news/mid/simroc-3---nyolc-uj-auto_2012-09-21-1348222495.jpg

Correct way to place an image tag within a php array loop

I wish to place an image tag within a PHP array, dynamically fed from a database. The array will eventually render directly onto a page.
What is the correct syntax for the image tag within the array; i.e. once the array is rendered on a page, the image tag should show as an image and not as simple text.
Perhaps it might be easier if I show you what I mean:
foreach($rows as &$row)
{
$this->_rows[] = array(
'thumnail' => '<img style="width: 180px; height: 80px;" src="<?= THUMBNAILn_Assets::getProductThumbnail($row->id) ?>" />',
);
};
The image tag renders as simple text on the page, as opposed to an image.
Try this :
foreach($rows as &$row)
{
$this->_rows[] = array(
'thumnail' => '<img style="width: 180px; height: 80px;" src="'. THUMBNAILn_Assets::getProductThumbnail($row->id) .'" />',
);
}
No need of php tags (<?= and ?>) again inside the src attribute
foreach($rows as &$row)
{
$t_pic['thumnail'] = THUMBNAILn_Assets::getProductThumbnail($row->id);
$this->_rows[] = $t_pic;
}
or
$t_pic['thumnail'] = '<img style="width: 180px; height: 80px;" src="'. THUMBNAILn_Assets::getProductThumbnail($row->id) .'" />';
just make it more clear and simple, its not good practice to store the html tags in php variables

Categories