はじめに
一つのサンプルになるべく DOMXPath クラス のメソッドを詰め込んでみました。
と言っても5つですが。
サンプル
$accountXml = <<<END_OF_XML <books> <book> <title>Great American Novel</title> <characters> <character> <name>Cliff</name> <desc>really great guy</desc> </character> <character> <name>Lovely Woman</name> <desc>matchless beauty</desc> </character> <character> <name>Loyal Dog</name> <desc>sleepy</desc> </character> </characters> <plot> Cliff meets Lovely Woman. Loyal Dog sleeps, but wakes up to bark at mailman. </plot> <success type="bestseller">4</success> <success type="bookclubs">9</success> </book> </books> END_OF_XML; $doc = new DOMDocument; $doc->loadXML($accountXml); $xpath = new DOMXPath($doc); $users = $xpath->query('/books/*'); var_dump($users); $usersCount = $xpath->evaluate('count(/books/book/characters/*)'); var_dump($usersCount); $nodelist = $xpath->query('/books/book[title="Great American Novel"]'); var_dump($nodelist->length); var_dump($nodelist->item(0)->nodeValue); $xpath->registerNamespace("php", "http://php.net/xpath"); $xpath->registerPHPFunctions(array('strpos')); $chars = $xpath->query('//books/book[title="Great American Novel"]/characters/' . 'character[php:functionString("strpos", name, "Dog") > 0]'); foreach ($chars as $char) { $name = $char->getElementsByTagName("name")->item(0)->nodeValue; $desc = $char->getElementsByTagName("desc")->item(0)->nodeValue; echo "$name : $desc<br />\n"; }