Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 747
Solace Avatar asked May 23 '15 19:05

Solace


2 Answers

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

$image_string = (string)$image
like image 160
pguardiario Avatar answered Sep 25 '22 17:09

pguardiario


Use outertext

$image_string = $image->outertext();

I looked in the code. function save return

$ret = $this->root->innertext();

But this is method of class simple_html_dom. After searching you receive object simple_html_dom_node. It hasn't such method and does not inherit. But has text, innertext and outertext.

like image 43
splash58 Avatar answered Sep 21 '22 17:09

splash58