-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathch8p5_2_DOM.php
More file actions
89 lines (85 loc) · 2.46 KB
/
ch8p5_2_DOM.php
File metadata and controls
89 lines (85 loc) · 2.46 KB
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
<?php
include_once('generalIncludes.php');
echo '<input id="chapter" type="hidden" value="8">';
echo '<h2>Chapter 8 Data Formats and Types - Paragraph DOM</h2>Loading and saving XML Documents, XPATH queries and Modifying XML documents<br/>
...next page for this paragraph<br/>';
echo '<h3>Listing 8.18: Adding an element with DOM</h3>';
showcode(<<<'CODE'
$dom = new DomDocument();
$dom->load("xml/library.xml");
$book = $dom->createElement("book");
$book->setAttribute("meta:isbn", "9781940111001");
$title = $dom->createElement("title");
$text = $dom->createTextNode("Mastering the SPL Library");
$title->appendChild($text);
$book->appendChild($title);
$author = $dom->createElement("author","Joshua Thijssen");
$book->appendChild($author);
$publisher = $dom->createElement(
"pub:publisher", "musketeers.me, LLC."
);
$book->appendChild($publisher);
$dom->appendChild($book);
print_r($dom);
CODE
);
//echo '<h3>Listing 8.19: Moving a node with DOM</h3>';
//showcode(<<<'CODE'
//$dom = new DomDocument();
//$dom->load("xml/library.xml");
//$xpath = new DomXPath($dom);
//$xpath->registerNamespace("lib",
// "http://example.org/library");
//$result = $xpath->query("//lib:book");
//$result->item(1)->parentNode->insertBefore(
// $result->item(1), $result->item(0)
//);
//print_r($result);
//CODE
//);
echo '<h3>Listing 8.20: Appending a node with DOM</h3>';
showcode(<<<'CODE'
$dom = new DomDocument();
$dom->load("xml/library.xml");
$xpath = new DomXPath($dom);
$xpath->registerNamespace("lib",
"http://example.org/library");
$result = $xpath->query("//lib:book");
print_r($result->item(0));
$newchild = $result->item(0);
$result->item(1)->parentNode->appendChild($newchild);
print_r($result);
CODE
);
echo '<h3>Listing 8.21: Duplicating a node with DOM</h3>';
showcode(<<<'CODE'
$dom = new DomDocument();
$dom->load("xml/library.xml");
$xpath->registerNamespace("lib",
"http://example.org/library");
$result = $xpath->query("//lib:book");
$clone = $result->item(0)->cloneNode();
$result->item(1)->parentNode->appendChild($clone);
print_r($result);
CODE
);
echo '<h3>Listing 8.22: Modifying XML with DOM</h3>';
showcode(<<<'CODE'
$xml = <<<XML
<xml>
<text>some text here</text>
</xml>
XML;
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DomXpath($dom);
$node = $xpath->query("//text/text()")->item(0);
$node->data = ucwords($node->data);
echo $dom->saveXML();
print_r($dom);
CODE
);
echo '';
showcode(<<<'CODE'
CODE
);