Search code examples
phpdommoodlesimple-html-domgettype

How to convert simple_html_dom object back to string?


I have used PHP Simple HTML DOM Parser to first convert an HTML string to DOM object by str_get_html() method of simple_html_dom.php

$summary = str_get_html($html_string);
  1. Then I extracted an <img> object from the $summary by

    foreach ($summary->find('img') as $img) {
        $image = $img;
        break;
    }
    

    Now I needed to convert $image DOM object back to a string. I used the Object Oriented way mentioned here:

    $image_string = $image->save();
    

    I got the error (from the Moodle debugger):

    Fatal error: Call to undefined method simple_html_dom_node::save() ...

  2. So I thought since I am working with Moodle, it may have something to do with Moodle, so I simply did the simple (non-object oriented?) way from the same manual:

    $image_string = $image;
    

    Then just to check/confirm that it has been converted to a string, I did:

    echo '$image TYPE: '.gettype($image);
    echo '<br><br>';
    echo '$image_string TYPE: '.gettype($image_string);
    

    But this prints:

    $image TYPE: object
    
    $image_string TYPE: object
    

So the question is Why??? Am I doing something wrong?


Solution

  • You just cast it to a string in the normal way:

    $image_string = (string)$image