PHP DOMXpath 클래스

1 개요[ | ]

PHP DOMXpath 클래스

2 예시: XML[ | ]

$xml = '<?xml version="1.0"?>
<moldb>
  <molecule>
    <name>Alanine</name>
    <symbol>ala</symbol>
    <code>A</code>
    <type>hydrophobic</type>
  </molecule>
  <molecule>
    <name>Lysine</name>
    <symbol>lys</symbol>
    <code>K</code>
    <type>charged</type>
  </molecule>
</moldb>';

$doc = new DOMDocument();
$doc->loadXML( $xml );

$xpath = new DOMXpath($doc);
$elements = $xpath->query("/moldb/molecule/symbol");
foreach( $elements as $element ) {
	echo $element->nodeValue.PHP_EOL;
}

3 예시: HTML[ | ]

$html = '<html>
<head>
<title>Welcome to zetawiki</title>
</head>
<body>
<p>My name is John</p>
</body>
</html>';

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$html_p = $xpath->query("//p");

for ($i = 0; $i < $html_p->length; $i++) {
    echo $html_p->item(0)->nodeValue;
}
$html = <<<EOF
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
$elements = $xpath->query("//a");
foreach( $elements as $elements ) {
    echo $elements->nodeValue . "\n";
}

4 같이 보기[ | ]

5 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}