라이브러리
[PHP] DOMElement::before - 요소 앞에 노드를 추가합니다.
DOMElement::before
PHP의 DOMElement::before 메서드는 DOMElement 객체의 내용 앞에 새로운 노드를 삽입합니다. 이 메서드는 DOMElement 객체의 내용을 변경하는 데 사용됩니다.
사용법
DOMElement::before 메서드는 두 개의 매개변수를 받습니다.
- `$targetNode`: 삽입할 노드의 위치를 지정하는 노드입니다.
- `$newNode`: 삽입할 새로운 노드입니다.
예제
#hostingforum.kr
php
// DOMDocument 객체를 생성합니다.
$doc = new DOMDocument();
$doc->loadXML('');
// DOMElement 객체를 생성합니다.
$root = $doc->documentElement;
$child1 = $root->firstChild;
$child2 = $root->lastChild;
// 새로운 노드를 생성합니다.
$newNode = $doc->createElement('newChild');
// 새로운 노드를 삽입합니다.
$child1->parentNode->insertBefore($newNode, $child1);
// DOMDocument 객체의 내용을 출력합니다.
echo $doc->saveXML();
위의 예제에서, 새로운 노드 `newChild`가 `child1` 앞에 삽입됩니다. 결과는 다음과 같습니다.
#hostingforum.kr
xml
예제 2: 노드의 내용을 변경하는 경우
#hostingforum.kr
php
// DOMDocument 객체를 생성합니다.
$doc = new DOMDocument();
$doc->loadXML('old content');
// DOMElement 객체를 생성합니다.
$root = $doc->documentElement;
$child1 = $root->firstChild;
// 새로운 내용을 생성합니다.
$newContent = $doc->createTextNode('new content');
// 새로운 내용을 삽입합니다.
$child1->parentNode->insertBefore($newContent, $child1->nextSibling);
// DOMDocument 객체의 내용을 출력합니다.
echo $doc->saveXML();
위의 예제에서, 새로운 내용 `new content`가 `child1`의 내용을 대체합니다. 결과는 다음과 같습니다.
#hostingforum.kr
xml
예제 3: 노드의 내용을 추가하는 경우
#hostingforum.kr
php
// DOMDocument 객체를 생성합니다.
$doc = new DOMDocument();
$doc->loadXML('old content');
// DOMElement 객체를 생성합니다.
$root = $doc->documentElement;
$child1 = $root->firstChild;
// 새로운 내용을 생성합니다.
$newContent = $doc->createTextNode(' new content');
// 새로운 내용을 삽입합니다.
$child1->appendChild($newContent);
// DOMDocument 객체의 내용을 출력합니다.
echo $doc->saveXML();
위의 예제에서, 새로운 내용 ` new content`가 `child1`의 내용의 뒤에 추가됩니다. 결과는 다음과 같습니다.
#hostingforum.kr
xml
old content new content
참고
- DOMElement::before 메서드는 노드의 내용을 변경하는 데 사용됩니다.
- 새로운 노드를 삽입할 때, 노드의 위치를 지정하는 노드를 매개변수로 받습니다.
- 새로운 노드는 DOMDocument 객체의 내용에 삽입됩니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.