CodeIgniter Forums
How to get first image from blog posts - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: How to get first image from blog posts (/showthread.php?tid=62319)



How to get first image from blog posts - chocovo - 07-02-2015

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.


RE: How to get first image from blog posts - gadelat - 07-03-2015

there isn't any image in some of your records


RE: How to get first image from blog posts - CroNiX - 07-03-2015

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.