#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    294
    Rep Power
    12

    Removing Image Height and Width attributes


    I'm assuming this is relatively easy, but I've never been good with the replace features in PHP and understanding the wild cards.

    All I'm trying to do is set up a PHP script that will scan for img tags and remove the height="XX" and width="XX" attributes. Which is to say:

    <img src="image.jpg" alt="XX" title="XX" height="XX" width="XX" />

    becomes

    <img src="image.jpg" alt="XX" title="XX" />

    Thanks for the help.
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,993
    Rep Power
    9397
    Load the HTML into DOMDocument, scan for all the images with getElementsByTagName(), remove the width and height attributes, and write back out the HTML.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    294
    Rep Power
    12
    Originally Posted by requinix
    Load the HTML into DOMDocument, scan for all the images with getElementsByTagName(), remove the width and height attributes, and write back out the HTML.
    I had no idea what you said even meant, but I was able to search for the terms you used and found an example of how to make it work that did precisely what I needed. For anyone else dealing with this here is what I did:

    PHP Code:
     <?php
    $html 
    '<img src="image.jpg" alt="XX" title="XX" height="XX" width="XX" />
    '
    ;
    $doc DOMDocument::loadhtml($content);
    foreach(
    $doc->getelementsbytagname('img') as $image){
        foreach(array(
    'width''height') as $attribute_to_remove){
            if(
    $image->hasattribute($attribute_to_remove)){
                
    $image->removeattribute($attribute_to_remove);
            }
        }
    }
    $content $doc->savehtml();
    ?>
    Thanks

    Comments on this post

    • requinix agrees : that's exactly what I was suggesting :D glad you went out of your way to research it

IMN logo majestic logo threadwatch logo seochat tools logo