• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get first image from blog posts

#1
Hello,

I am trying to get the first image of the text field "blog_post_content" and copy it to the field "blog_post_image".

I was looking on the Internet and tried something but I have an error.

In the controller I have this function:
PHP Code:
public function getfirstimage() {
        
$sql "SELECT blog_post_id, blog_post_content FROM tbl_blog_post";

        
$query $this->db->query($sql);
        if (
$query->num_rows() > 0) {
            foreach (
$query->result() as $row) {
                
$id $row->blog_post_id;
                
$texthtml $row->blog_post_content;
                
$first_img '';
                
$output preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i'$texthtml$matches);
                
$first_img $matches[1][0];
                
$data = array('blog_post_image' => $first_img);
                
$this->db->where('blog_post_id'$id);
                
$this->db->update('tbl_blog_post'$data);
            }
        }
    } 

The error is:
PHP Code:
MessageUndefined offset... in line "$first_img = $matches[1][0];" 

Can somebody help me with it?
Thank you.
Reply

#2
there isn't any image in some of your records
Reply

#3
If you're only trying to get the FIRST image, why use preg_match_all() which will get ALL images? Try using just preg_match() and then testing if $matches[1] exists before trying to use it. Additionally preg_match() will be slightly faster since it will stop trying to match after it finds the first entry if one exists:

$first_img = isset($matches[1]) ? $matches[1] : ''; //$first_img will be image, or empty string if it didn't exist.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.