如何操作 PHP dom?
- the CRUD of php node
A. Create
A-1. create node
- create a node
$element = $dom->createElement('div', 'text');
- attach $element as a child of $parent (把新增的 $element 加到 $parent 底下)
$parent->appendChild($element);
https://www.php.net/manual/en/domdocument.createelement.php
A-2. copy a node
$dom->cloneNode($deep = false)
- $deep defaulted false
- copy first child of nodes (僅複製第一層的子節點)
$element = $dom->cloneNode();
$element = $dom->cloneNode(false);
- copy all descendant nodes (複製所有的子節點)
$element = $dom->cloneNode(true);
- The reference of a node will be moved after cloning it.
- 注意,在 cloneNode 之後,就沒辦法使用
$element-> parentNode()
找到它的父層
- 注意,在 cloneNode 之後,就沒辦法使用
https://www.php.net/manual/en/domnode.clonenode.php
B. Read
B-1. get nodes with the specified tag name (找到有某個 tag name 的 node)
$div = $dom->getElementsByTagName('div');
B-2. about attribute
- DOMElement::
hasAttribute()
- Checks to see if attribute exists
- DOMElement::
setAttribute()
- Adds new attribute
- DOMElement::
removeAttribute()
- Removes attribute
- example
$searchNode->getAttribute('ID');
https://www.php.net/manual/en/domelement.getattribute.php
C. Update
C-1. replace current node
$href->parentNode->removeChild($href);
$node->parentNode->parentNode->removeChild($node->parentNode);
D. Delete
D-1. remove a node
- from end to start (記得從最後一個往前)
- the order will changed while replacing (因為置換之後,會改變編號)
1
2
3
4
5$elements = $completePage->getElementsByTagName('a');
for ($i = $elements->length; --$i >= 0; ) {
$href = $elements->item($i);
$href->parentNode->removeChild($href);
}
- the order will changed while replacing (因為置換之後,會改變編號)
- https://stackoverflow.com/questions/15272726/how-to-delete-element-with-domdocument