php DOMDocument How to convert node value to string

12,541

Use saveXML() or saveHTML() on each node to add it to an array:

$img_links = array();
$domimg = new DOMDocument();
$domimg->loadHTML($body);
$images_all = $domimg->getElementsByTagName('img');

foreach ($images_all as $image) {
  // Append the XML or HTML of each to an array
  $img_links[] = $domimg->saveXML($image);
}

print_r($img_links);
Share:
12,541
user191688
Author by

user191688

Updated on June 04, 2022

Comments

  • user191688
    user191688 about 2 years

    Possible Duplicate:
    How can I get an element's serialised HTML with PHP's DOMDocument?
    PHP + DOMDocument: outerHTML for element?

    I am trying to extract all img tags from a string. I am using:

    $domimg = new DOMDocument();
    @$domimg->loadHTML($body);
    $images_all = $domimg->getElementsByTagName('img');
    
    foreach ($images_all as $image) {
      // do something
    }
    

    I want to put the src= values or even the complete img tags into an array or string.

  • user191688
    user191688 over 12 years
    Thanks @Michael. That was what I needed. I had tried saveXML but I was using it incorrectly.