0

I have a string that contains text and photos as you can see bellow. My code so far get all the images and upload them into a folder. I need to replace the new uploaded links with the correct oreder.

$nextstep = "Hello there this is image 1 <img src='http://www.demosite.com/wp-content/uploads/2015/01.jpg' width='653' height='340' alt='xxx' title='xxx'> !! And Now you can see image number 2 <img src='http://www.demosite.com/wp-content/uploads/2015/02.jpg' width='653' height='340' alt='xxx' title='xxx'>";

$string = $nextstep;
$doc = new DOMDocument();
$doc->loadHTML($string);
$images = $doc->getElementsByTagName('img');
foreach ($images as $image) { //STARTING LOOP
    echo "</br>";
    echo $image->getAttribute('src') . "\n";
    echo "</br>";
    $urlimg = $image->getAttribute('src'); //IMAGE URL
    $URL = urldecode($urlimg);
    $image_name = (stristr($URL,'?',true))?stristr($URL,'?',true):$URL;
    $pos = strrpos($image_name,'/');
    $image_name = substr($image_name,$pos+1);
    $extension = stristr($image_name,'.');
    if($extension == '.jpg' || $extension == '.png' || $extension == '.gif' || $extension == '.jpeg'){
        $img = '../images/' . $image_name;
        file_put_contents($img, file_get_contents($url)); //UPLOAD THEM ONE BY ONE
    }
}
3
  • 1
    What is the correct order and how is that defined? Commented Oct 10, 2015 at 22:19
  • fo e.g "hello you can see the flower (image of a flower), and now you can see a tree (image of a tree) so replaced urls must be the flower first and the tree the second Commented Oct 10, 2015 at 23:42
  • But when are reading them how do you know what is first vs. second/third/etc... or is this a one time run? Commented Oct 11, 2015 at 5:06

1 Answer 1

3

It's not clear what the desired outcome is here. It sounds like you want to change the src URL in your existing string to the one where you've saved the images. If this isn't the case please do try updating the question for more clarity.

Here's a simple way to break down the problem...

Step 1 - Extract the img tags from DOM using source string

$html = <<<'HTML'
Hello there this is image 1 <img src="http://www.demosite.com/wp-content/uploads/2015/01.jpg" width="653" height="340" alt="xxx" title="xxx"> !! 

And Now you can see image number 2 <img src="http://www.demosite.com/wp-content/uploads/2015/02.jpg" width="653" height="340" alt="xxx" title="xxx">
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html);
$imgs = $dom->getElementsByTagName('img');

// Store the list of image urls in an array - this will come in handy later
$imgURLs = [];
foreach($imgs as $img) {
    if (!$img->hasAttribute('src')) {
        continue;
    }
    $imgURLs[] = $img->getAttribute('src');
}

Step 2 - Save the image in a different location

$newImgURLs = [];          // new modified URLs where images were moved
$newPath    = '../images'; // wherever you're saving the images
foreach($imgURLs as $imgURL) {
    /**
     *  Use parse_url and pathinfo to break down the URL parts and extract the
     *  filename/extension instead of the fragile implementation you used above
     */
    $URLparts     = parse_url($imgURL);
    $file         = pathinfo($URLparts['path']);
    $fileName     = $file['filename'] . '.' . $file['extension'];
    $newFileName  = $newPath . '/' . $fileName;
    $newImgURLs[] = $URLparts['scheme'] . '://' .
                    $URLparts['host'] . $file['dirname'] . '/' . $newFileName .
                    (isset($URLparts['query']) ? ('?' . $URLparts['query']) : null) .
                    (isset($URLparts['fragment']) ? ('#' . $URLparts['fragment']) : null);
    // download image and save to new location
    file_put_contents($newFileName, file_get_contents($imgURL));
}

Step 3 - Modify the img src URLs to new path

foreach($imgs as $i => $img) {
    $img->setAttribute('src', $newImgURLs[$i]);
}
echo $dom->saveHTML(); // new updated DOM
// or just create a new $html string from scratch using the new URLs.
Sign up to request clarification or add additional context in comments.

7 Comments

this $imgURLs = []; is marked as error. do you know why?
Probably because you're using an unsupported version. Short-hand array syntax has been around since PHP 5.4.0 and if you're using anything older than that you're way out of date. See PHP EOL reference for more information and which versions of PHP are no long supported.
images are uploaded but in new echo $dom->saveHTML(); it shows the old url. Do you believe that the problem is that Short hand array is highlited as an error? is there any compatible way? Thank you so much for your time Sir. I am using php 5.5.3
If you were using PHP 5.5.3, you would not get a syntax error for that. Perhaps share the actual error? It might be something else?
i found out that all image srcs keep the original url and added ../images/uploaded image . jpg so i need to remove this original url
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.