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 />”;
}
}
?>
cy.php输出结果为:
1
2
3
4
5
6
为什么
<m>
<list>7</list>
<list>8</list>
<list>9</list>
</m>
中的7,8,9没有被读出来?
因为我们的cy.php只读取<main></main>标记中的内容.<m></m>标记中的内容是不会被读取的.
我们这里所提到的”标记”,在XML里被称做”节点”;
关于”节点”的相关概念,我们将在以后说明.
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 />”;