How to convert simple_html_dom object back to string?
Asked Answered
E

3

7

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?

Enthronement answered 23/5, 2015 at 19:42 Comment(0)
A
5

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

$image_string = (string)$image
Abhor answered 23/5, 2015 at 22:36 Comment(1)
Oh this is great. I didn't try it. Thanks.Enthronement
S
3

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.

Scrounge answered 23/5, 2015 at 20:4 Comment(4)
Thanks, but this is a good "hack", right? DO you have any idea why don't the methods described in the manual work?Enthronement
It's from docs :) I use only such way and don't know about save :)Scrounge
Here! See the section titled 'How to dump contents of DOM object?' and click the tabs titled 'Quick way' and 'Object-oriented way'.Enthronement
I am wrong. Save must work but return full tree, not the object. So why i never used it :)Scrounge
S
1

$image->text(); this worked for me

Sherri answered 23/5, 2015 at 20:6 Comment(2)
I can't find the text() function in the API referenceEnthronement
yup this is not in the api reference but when you var_dum($image) you will see this methodSherri

© 2022 - 2024 — McMap. All rights reserved.