joakim.g
joakim.g

Reputation: 71

Get images from article in Joomla with php

I'm trying edit a plugin which I use to add meta open graph tags to the header. The problem with it is that it would only let me choose one picture for the whole site.. this is what I've done:

preg_match_all('/<img .*?(?=src)src=\"([^\"]+)\"/si', $hdog_base, $image);

if (strlen($hdog_base) <= 25) 
{
    if (substr($image[0], 0, 4) != 'http') 
    {
        $image[0] = JURI::base().$image[0]; 
    }
    $hdog_image_tmp = $image[0];
}
else
{
    if (substr($image[1], 0, 4) != 'http') 
    {
        $image[1] = JURI::base().$image[1]; 
    }
    $hdog_image_tmp = $image[1];
}
$hdog_image =   '<meta property="og:image" content="'.$hdog_image_tmp.'" />
';

$hdog_base is the current webpage I'm on. The first if-statement would show the very first picture, which is the logo (used for ex. homepage), and the else would show the second picture (which would be different on each page), but the result only comes out like this, no matter if I'm on the homepage or anywhere else on the site:

<meta property="og:image" content="http://mysite.com/Array" />

Any suggestions?

Thanks in advance,

Update: The biggest fault I'm making is that I am trying to find the images in a url, not the actual webpage. But just the link. So how would I go on to get the contents of the current page in a string? Instead of $hdog_base, which is nothing but a link.

UPDATE, SOLVED:

I used

$buffer = JResponse::getBody();

to get the webpage in HTML

and then DOM for the rest

$doc = new DOMDocument();
@$doc->loadHTML($buffer);

$images = $doc->getElementsByTagName('img');
if (strlen($hdog_base) <= 26) 
{
    $image = $images->item(0)->getAttribute('src');
} 
else 
{
    $image = $images->item(1)->getAttribute('src');
}
if (substr($image, 0, 4) != 'http') $image = JURI::base().$image;
$hdog_image =   '<meta property="og:image" content="'.$image.'" />
';

Thanks a lot cpilko for your help! :)

Upvotes: 2

Views: 4461

Answers (1)

cpilko
cpilko

Reputation: 11852

Using preg_match_all with more than one subpattern in the regular expression will return a multidimensional array. In your code $image[n] is an array. If you cast an array as a string in php, as you are doing it returns the text Array.

EDIT: Using a regex to parse HTML isn't ideal. You are better off doing it with DOMDocument:

$doc = new DOMDocument();
@$doc->loadHTML($hdog_base);

$images = $doc->getElementsByTagName('img');
if (strlen($hdog_base) <= 25) {
    $image = $images->item(0)->getAttribute('src');
} else {
    $image = $images->item(1)->getAttribute('src');
}
if (substr($image[0], 0, 4) != 'http') $image .= JURI::base();
$hdog_image =   '<meta property="og:image" content="'.$hdog_image_tmp.'" />
';

Upvotes: 3

Related Questions