Completed
Push — SOLID ( b14133...a3f21e )
by Wouter
02:08
created

HtmlToJson::toJson()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 25
rs 8.8571
cc 3
eloc 12
nc 2
nop 1
1
<?php
2
3
namespace Sioen;
4
5
/**
6
 * Class HtmlToJson
7
 *
8
 * Converts html to a json object that can be understood by Sir Trevor
9
 *
10
 * @version 1.1.0
11
 * @author Wouter Sioen <[email protected]>
12
 * @license http://www.opensource.org/licenses/mit-license.php MIT
13
 */
14
class HtmlToJson
15
{
16
    /**
17
     * Converts html to the json Sir Trevor requires
18
     *
19
     * @param  string $html
20
     * @return string The json string
21
     */
22
    public function toJson($html)
23
    {
24
        // Strip white space between tags to prevent creation of empty #text nodes
25
        $html = preg_replace('~>\s+<~', '><', $html);
26
        $document = new \DOMDocument();
27
28
        // Load UTF-8 HTML hack (from http://bit.ly/pVDyCt)
29
        $document->loadHTML('<?xml encoding="UTF-8">' . $html);
30
        $document->encoding = 'UTF-8';
31
32
        // fetch the body of the document. All html is stored in there
33
        $body = $document->getElementsByTagName("body")->item(0);
34
35
        $data = array();
36
37
        // loop trough the child nodes and convert them
38
        if ($body) {
39
            foreach ($body->childNodes as $node) {
40
                $toJsonContext = new ToJsonContext($node->nodeName);
41
                $data[] = $toJsonContext->getData($node);
42
            }
43
        }
44
45
        return json_encode(array('data' => $data));
46
    }
47
}
48