php教程 DOM解析xml文档实例

<?php
// php教程 domdocument 解析xml文档实例

// 解析xml实例一
$objDOM = new DOMDocument();
$objDOM->load("xml.xml");
$parent = $objDOM->getElementsByTagName("Product");
foreach( $parent as $value )
{
	$names = $value->getElementsByTagName("Name");
	$name  = $names->item(0)->nodeValue;

	$urls = $value->getElementsByTagName("Url");
	$url  = $urls->item(0)->nodeValue;

	$images = $value->getElementsByTagName("Image");
	$image  = $images->item(1)->nodeValue;
}

// DOMDocument实例二
$xml = new DOMDocument();
$xml->load("me.xml");
$postDom = $xml->getElementsByTagName("post");
foreach($postDom as $post){
	$title = $post->getElementsByTagName("title");
	echo "Id: " . $title->attributes->item(0)->nodeValue . "<br />";
	echo "Title: " . $title->item(0)->nodeValue . "<br />";
	echo "Details: " . $post->getElementsByTagName("details")->item(0)->nodeValue . "<br /><br />";
}
?>


xml.xml

<?xml version="1.0" encoding="UTF-8"?>
<Root>
<Category>
<Product>
<Name>网页制作教程教程</Name>
<Image>
<SizeName>Small</SizeName>
<Url>http://www.111cn.net</Url>
</Image>
<Image>
<SizeName>Medium</SizeName>
<Url>http://www.111cn.net</Url>
</Image>
<Image>
<SizeName>Large</SizeName>
<Url>http://www.111cn.net</Url>
</Image>
</Product>
</Category>
</Root>
me.xml;

<?xml version="1.0" encoding="utf-8"?>
<phplamp>
<post>
<title id="1">PHP XML处理介绍一</title>
<details>详细内容一</details>
</post>
<post>
<title id="2">PHP XML处理介绍二</title>
<details>详细内容二</details>
</post>
<post>
<title id="3">PHP XML处理介绍三</title>
<details>详细内容三</details>
</post>
</phplamp>

你可能感兴趣的:(PHP,xml,.net)