aboutsummaryrefslogtreecommitdiff
path: root/app/model/HTMLExtract.php
blob: 5c3f7270e694010ad2501bf8b01002642c4d08e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php

class DOMExtract extends DOMDocument
{
    private $source;
    private $document;

    public function __construct()
    {
        libxml_use_internal_errors(true);
        $this->preserveWhiteSpace = false;
        $this->strictErrorChecking = false;
        $this->formatOutput = true;
    }

    public function setSource($source)
    {
        $this->source = file_get_contents($source);
        return $this;
    }

    public function getInnerHTML($tag, $id=null, $nodeValue = false)
    {
        if (empty($this->source)) {
            throw new Exception('Error: Missing $this->source, use setSource() first');
        }

        $html = null;
        $this->loadHTML($this->source);
        $element = $this->getElementsByTagName($tag);

        foreach ($element as $tags) {
            if ($id !== null) {
                $attr = explode('=', $id);
                if ($tags->getAttribute($attr[0]) == $attr[1]) {
                    if ($nodeValue == true) {
                        $html .= trim($tags->nodeValue);
                    } else {
                        $html .= $this->innerHTML($tags);
                    }
                }
            } else {
                if ($nodeValue == true) {
                    $html .= trim($tags->nodeValue);
                } else {
                    $html .= $this->innerHTML($tags);
                }
            }
        }
        return $html;
    }

    protected function innerHTML($document)
    {
        $html = "";
        foreach ($document->childNodes as $v) {
            $tmp = new DOMDocument();
            $tmp->appendChild($tmp->importNode($v, true));
            $html .= trim($tmp->saveHTML());
        }
        return $html;
    }

}