PHP读取XML 值 - PHP读取XML 内容 (三)

发布时间:2008年08月15日      浏览次数:795 次
Php读取XML情况六,再foreach一次,我们把7,8,9读出来!:
XML文件(cy.xm)如下:
<?xml version="1.0" encoding="gb2312"?>
<xml>
<main>
<list>1</list>
<list>2</list>
<list>3</list>
</main>
<main>
<list>4</list>
<list>5</list>
<list>6</list>
</main>
<m>
<list>7</list>
<list>8</list>
<list>9</list>
</m>
</xml>
Php文件(cy.php)如下:
<?php
$xml = new DOMDocument();
$xml->load('cy.xml');
$main = $xml->getElementsByTagName('main');
foreach( $main as $main)
{
$list = $main->getElementsByTagName( "list" );
foreach ( $list as $list )
{
$value = $list->firstChild->nodeValue;
echo $value."<br />";
}
}
$m = $xml->getElementsByTagName('m');
foreach( $m as $m)
{
$list = $m->getElementsByTagName( "list" );
foreach ( $list as $list )
{
$value = $list->firstChild->nodeValue;
echo $value."<br />";
}
}
?>
cy.php输出结果:
1
2
3
4
5
6
7
8
9
===============
Php读取XML情况七,cy.xml变得更复杂一些:
XML文件(cy.xml)如下:
<?xml version="1.0" encoding="gb2312"?>
<xml>
<main>
<title>a</title>
<list>1</list>
<list>2</list>
<list>3</list>
</main>
<main>
<title>b</title>
<list>4</list>
<list>5</list>
<list>6</list>
</main>
<m>
<title>c</title>
<list>7</list>
<list>8</list>
<list>9</list>
</m>
</xml>
那么,我们如何只读出<main></main>内<title></title>中的值呢?
Php文件(cy.php)如下:
<?php
$xml = new DOMDocument();
$xml->load('cy.xml');
$main = $xml->getElementsByTagName('main');
foreach( $main as $main)
{
$list = $main->getElementsByTagName( "list" );
foreach ( $list as $list )
{
$value = $list->firstChild->nodeValue;
echo $value."<br />";
}
$title = $main->getElementsByTagName( "title" );
foreach ( $title as $title )
{
$value = $title->firstChild->nodeValue;
echo $value."<br />";
}
}
$m = $xml->getElementsByTagName('m');
foreach( $m as $m)
{
$list = $m->getElementsByTagName( "list" );
foreach ( $list as $list )
{
$value = $list->firstChild->nodeValue;
echo $value."<br />";
}
}
?>
cy.php输出结果:
1
2
3
a
4
5
6
b
7
8
9
想一下,如何读出<m>中<title></title>的值?
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!