Tuesday, 15 January 2013

html - In PHP, how can I use the DOMDocument class to replace the src= attribute of an IMG tag? -


It is often able to swap out featuring src = an HTML IMG tag without losing any of the other characteristics Useful for What is a quick, non-regex way to do

reasons I do not want to use that want to are the regular expressions are:

  1. It's not very readable is. I do not want to spend 20 minutes of repeating a pattern every time I need an account for a new case.
  2. I am planning to modify this function when they have disappeared, to add width and height attributes. String replacement from a simple regular expression will not be easy to modify for this purpose

    Here is the reference:. I have a group of RSS feed posts that contain every single image. I want to replace these images with clear images, but HTML Otherwise unaffected:

      $ raw_post_html = "& LT; h2 & the gt; feed example & lt; / h2 & gt; & lt; p class = 'feedBody' & gt; & lt; img src = 'http: //premium.mofusecdn.com/6ff7098b3c8561d70c0af16d30e57d4e/cache/other/48da8425bc54af2d5d022f28cc8b021c.200.0.0.png' alt = 'feed Post Image 'width =' 350 'height =' 200 '/ & gt; Feed body content & lt; / p & gt; "; Echo replacement _img_src ($ raw_post_html, "http://cdn.company.org/blank.gif");    

    I This is what I came up. It uses the PHP DOM API to create a small HTML document, then saves XML only for the IMG element.

      function replace_img_src ($ original_img_tag, $ new_src_url) {$ doc = new DOMDocument (); $ Doctor & gt; LoadHTML ($ original_img_tag); $ Tag = $ doc- & gt; GetElementsByTagName ('IMG'); If (Count ($ tag)> 1) {$ tag = $ tags-> Item (0); $ Tag- & gt; Set attribute ('src', $ new_src_url); $ Doc- & gt; Return HTML ($ Tag) Return; } return false; }   

    Note : In PHP versions prior to 5.3.6, $ doc- & gt; Save HTML ($ tag) can be changed to $ doc- & gt; Save XML ($ tag) .

No comments:

Post a Comment