nested-data-via-dom

Gesponsorde koppelingen

PHP script bestanden

  1. nested-data-via-dom

« Lees de omschrijving en reacties

Code (php)
PHP script in nieuw venster Selecteer het PHP script
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
<?php

// Nested.php

include 'Nested/Exception.php';
include 'Nested/Child.php';
include 'Nested/Children.php';
include 'Nested/Child/Properties.php';


class Nested {

    /**
     *
     * @var DOMDocument
     */

    protected $doc;

    /**
     * Properties stack
     * Each instance of Nested has its own array in this collection. The key of that array is the
     * instance id
     * @var array
     */

    static public $propertiesCollection = array();

    /**
     * The number of instances of Nested
     * @var int
     */

    static protected $instance_count = 0;

    /**
     * The instance number. this is the key for the properties array of self::$propertiesCollection
     * @var int
     */

    protected $instance_id;

    /**
     * If an element is added, when the parent element isn't already added, the element
     * will stored (temporary) in this array
     *
     * @var array
     */

    protected $noParentCollection = array();

    /**
     * Create the DOMDocument object
     */

    public function __construct(){
        $this->instance_id = ++self::$instance_count;
        self::$propertiesCollection[$this->instance_id] = array();
        $this->doc = new DOMDocument();
    }


    /**
     *
     * @param $id
     * @param $parent_id
     * @param $properties
     * @return unknown_type
     */

    public function addChild($id,$parent_id=0,$properties=array()){
        if(!(ctype_digit($id) || is_int($id)) || $id <= 0 || isset(self::$propertiesCollection[$this->instance_id][$id])){
            throw new Nested_Exception('The ID must be a unique positive integer');
        }


        // Properties
        self::$propertiesCollection[$this->instance_id][$id] = new Nested_Child_Properties($properties);

        // Create the element
        $newElmt = $this->doc->createElement('child');

        // Add ID attribute
        $idAttr = $this->doc->createAttribute('id');
        $idAttr->appendChild($this->doc->createTextNode('id'.$id));
        $newElmt->appendChild($idAttr);
        $newElmt->setIdAttribute('id',true);

        // Add the other attributes. These attributes can you use to create xPath queries
        foreach($properties as $key => $property){
            if($key != 'id'){
                $attr = $this->doc->createAttribute((string)$key);
                $attr->appendChild($this->doc->createTextNode((string)$property));
                $newElmt->appendChild($attr);
            }
        }


        // If there's a parent element found, append this new element to the parent element
        if($parent_id > 0){
            $parentElmt = (int)$parent_id > 0 ? $this->doc->getElementById('id'.$parent_id) : null;
            if($parentElmt instanceof DOMElement){
                $parentElmt->appendChild($newElmt);
            }
else{
                // The parent is not found, save the element and wait till the parent element
                // gets added

                $this->noParentCollection[$parent_id] = $newElmt;
            }
        }
else{
            $this->doc->appendChild($newElmt);
        }


        // There is a child element of this element who is already added
        if(isset($this->noParentCollection[$id])){
            $newElmt->appendChild($this->noParentCollection[$id]);
            unset($this->noParentCollection[$id]);
        }
    }


    /**
     *
     * @param int $id
     * @return Nested_Child
     */

    public function getElement($id){
        $elmt = $this->doc->getElementById('id'.$id);
        if($elmt instanceof DOMElement){
            return new Nested_Child($elmt,$this->instance_id);
        }

        throw new Nested_Exception('This element does not exists');
    }


    /**
     * Get the elements at the 'root' level
     * @return Nested_Children
     */

    public function getElements(){
        $childElmts = $this->doc->childNodes;
        $children = new Nested_Children();
        foreach($childElmts as $elmt){
            $children->addChild(new Nested_Child($elmt,$this->instance_id));
        }

        return $children;
    }


    /**
     * You can run xPath queries too to select child elements
     * @param string $query
     * @return unknown_type
     */

    public function xPath($query){
        $xpath = new DOMXPath($this->doc);
        $result = $xpath->evaluate($query);
        if($result instanceof DOMNodeList){
            $children = new Nested_Children();
            foreach($result as $elmt){
                if($elmt instanceof DOMElement){
                    $children->addChild(new Nested_Child($elmt,$this->instance_id));
                }
            }

            return $children;
        }

        return $result;
    }


    /**
     * Shows the hierarchy in XML
     * @param int $id If you want to view the hierarchy of an element
     * @return void
     */

    public function debug($id=null){
        $this->doc->formatOutput = true;

        $node = null;
        if(!empty($id)){
            $node = $this->getElement($id)->getDOMElement();
        }

        echo '<pre>'.htmlentities($this->doc->saveXML($node),true).'</pre>';
    }


    /**
     * Clear the memory
     * @return void
     */

    public function __destruct(){
        unset($this->doc);
    }

}




// Nested/Child.php

class Awf_Nested_Child {

    /**
     *
     * @var DOMElement
     */

    protected $elmt;

    /**
     *
     * @var int
     */

    protected $id;

    protected $nested_instance_id;

    /**
     *
     * @param DOMElement $elmt
     */

    public function __construct(DOMElement $elmt,$nested_instance_id){
        $this->elmt = $elmt;
        $this->nested_instance_id = $nested_instance_id;
    }


    /**
     * Get the element ID
     * @return int
     */

    public function getId(){
        if(empty($this->id)){
            $this->id = (int) substr($this->elmt->getAttribute('id'),2);
        }

        return $this->id;
    }


    /**
     * Get the parent element
     * @return Awf_Nested_Child
     */

    public function getParent(){
        $parent = $this->elmt->parentNode;
        if($parent instanceof DOMElement){
            return new Awf_Nested_Child($parent,$this->nested_instance_id);
        }

        throw new Awf_Nested_Exception('This parent element does not exists');
    }


    /**
     * Get the element properties
     * @return Awf_Nested_Child_Properties
     */

    public function getProperties(){
        $properties = isset(Awf_Nested::$propertiesCollection[$this->nested_instance_id][$this->getId()]) ?
            Awf_Nested::$propertiesCollection[$this->nested_instance_id][$this->getId()] :
            new
Awf_Nested_Child_Properties(array());
        return $properties;
    }


    /**
     * Check if the element has child nodes
     * @return bool
     */

    public function hasChildren(){
        return $this->elmt->hasChildNodes();
    }


    /**
     * Get the element children
     * @return Awf_Nested_Children
     */

    public function getChildren(){
        $childElmts = $this->elmt->childNodes;
        $children = new Awf_Nested_Children();
        foreach($childElmts as $elmt){
            $children->addChild(new Awf_Nested_Child($elmt,$this->nested_instance_id));
        }

        return $children;
    }


    /**
     *
     * @return DOMElement
     */

    public function getDOMElement(){
        return $this->elmt;
    }
}



// Nested/Children.php


class Nested_Children implements Iterator, Countable {

    /**
     * The children
     *
     * @var array
     */

    protected $children = array();

    /**
     * Add a child
     *
     * @param Nested_Child $child
     */

    public function addChild(Nested_Child $child){
        $this->children[$child->getId()] = $child;
    }


    /**
     * Get a child
     *
     * @param string $key The ID of the child
     * @return Nested_Child
     */

    public function __get($key){
        if(isset($this->children[$key])){
            return $this->children[$key];
        }

        return false;
    }


    /**
     * If the Child is already added to the children
     *
     * @param string $key The ID of the child
     * @return bool true if the child isset, otherwise false
     */

    public function __isset($key){
        return isset($this->children[$key]);
    }


    /**
     * Count the children
     *
     * @return int
     */

    public function count(){
        return count($this->children);
    }



    /**
     *
     * @return bool
     */

    public function rewind() {
        reset($this->children);
    }


    /**
     *
     * @return Nested_Child
     */

    public function current() {
        return current($this->children);
    }


    /**
    * @var string|int
     */

    public function key() {
        return key($this->children);
    }


    /**
     *
     * @return Nested_Child|false
     */

    public function next() {
        return next($this->children);
    }


    /**
     *
     * @return bool
     */

    public function valid() {
        return $this->current() !== false;
    }
}



// Nested/Child/Properties.php


class Nested_Child_Properties implements Iterator, Countable {

    /**
     * The properties of a element
     *
     * @var array
     */

    protected $properties = array();

    /**
     * Create a properties instance
     *
     * @param array $properties
     */

    public function __construct(array $properties){
        $this->properties = $properties;
    }


    /**
     * Return a property
     *
     * @param string $key Property Key
     * @return mixed The property value, if the property does not exists, it returns false
     */

    public function __get($key){
        if(isset($this->properties[$key])){
            return $this->properties[$key];
        }

        return false;
    }


    /**
     * Set a property
     *
     * @param string $key
     * @param mixed $value
     */

    public function __set($key,$value){
        $this->properties[$key] = $value;
    }


    /**
     * Checks if the property isset
     *
     * @param string $key
     * @return bool True if the property isset, otherwise false
     */

    public function __isset($key){
        return isset($this->properties[(string)$key]);
    }


    public function count(){
        return count($this->properties);
    }


    /**
     * Make the properties iteratable
     */


    public function rewind() {
        reset($this->properties);
    }


    public function current() {
        return current($this->properties);
    }


    public function key() {
        return key($this->properties);
    }


    public function next() {
        return next($this->properties);
    }


    public function valid() {
        return $this->properties() !== false;
    }

}


// Nested/Exception.php

class Nested_Exception extends Exception {
        
}



// Voorbeeld

$i = 1;

$nested = new Nested();

// Elementen toevoegen
$nested->addChild($i,0,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));
$nested->addChild($i,0,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));

// Zoals je ziet, heeft dit element de parent met id=5. Deze is helaas nog
//niet toegevoegd. Daarom zal dit element even tijdelijk worden opgeslagen
//en wordt alsnog toegevoegd als child van id=5 als het element met id=5
//toegevoegd wordt.

$nested->addChild($i,5,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));

$nested->addChild($i,1,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));

// Nu wordt dus het element met ID=3 toegevoegd aan dit element
$nested->addChild($i,2,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));
$nested->addChild($i,2,array('id'=>$i++,'naam'=>'bar','tekst'=>'foo'));

$children = $nested->getElement(1)->getChildren();
foreach($children as $child){
    echo $child->getProperties()->tekst.'<br />';
}


echo $nested->getElement(4)->getParent()->getProperties()->naam;

$nested->debug();

?>

 
 

Om de gebruiksvriendelijkheid van onze website en diensten te optimaliseren maken wij gebruik van cookies. Deze cookies gebruiken wij voor functionaliteiten, analytische gegevens en marketing doeleinden. U vindt meer informatie in onze privacy statement.