按ID过滤XML文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了按ID过滤XML文件相关的知识,希望对你有一定的参考价值。
您好我在尝试解析XML文件时遇到问题
我试图仅使用id显示一首歌曲内容
mysongs.php?id = 0它应该显示“我离开了我的心脏在欧罗巴”的歌曲
如果mysongs.php?id = 1
它应该显示“Oh Ganymede”的歌曲
我想使用ID代替歌曲数字我的问题是当我使用[$id]
而不是数字[0]
不起作用
echo $mysongs->song[$id]->title;
请问我该如何解决我的问题
这是我的XML文件内容songs.xml
<album>
<song dateplayed="2011-07-24 19:40:26">
<title>I left my heart on Europa</title>
<artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
<title>Oh Ganymede</title>
<artist>Beefachanga</artist>
</song>
</album>
我的PHP代码如下
<?php
$id = $_GET['id'];
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->title;
?>
您需要将id设置为xml文件中column参数的一部分
请尝试以下代码
<album>
<song dateplayed="2011-07-24 19:40:26">
<id>1</id>
<title>I left my heart on Europa</title>
<artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
<id>2</id>
<title>Oh Ganymede</title>
<artist>Beefachanga</artist>
</song>
</album>
您可以使用以下两种方法获得结果
1.)使用直接元素法
以下示例获取“.xml”文件中第一个和第二个元素中的and元素的节点值:
<?php
$id = $_GET['id'];
$mysongs = simplexml_load_file('songs.xml')or die("Error: Cannot create object");
//get the first record
echo $mysongs->song[0]->id;
echo $mysongs->song[0]->title;
//get the second record
echo $mysongs->song[1]->id;
echo $mysongs->song[1]->title;
?>
2.)使用Element循环方法
<?php
$mysongs=simplexml_load_file("songs.xml") or die("Error: Cannot create object");
foreach($mysongs->children() as $song_album) {
echo $song_album->id . ", ";
echo $song_album->title . ", ";
echo $song_album->artist . "<br>";
}
?>
这可能是一个类型问题。
尝试回显你的id的类型,除非你在某处解析它将是一个字符串:
<?php
$id = $_GET['id'];
echo gettype($id);
然后,当你做$mysongs->song[$id]
时,它不是$mysongs->song[0]
的等价物,而是与$mysongs->song['0']
不同的指数。
因此,要获得预期的输出,您应该在将其用作索引之前将其强制转换为int。为此,您可以使用强制转换($id = (int) $_GET['id'];
),或者在PHP版本中使用intval($id = intval($_GET['id']);
)
然后最终结果看起来像......
<?php
$id = (int) $_GET['id'];
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[$id]->title;
以上是关于按ID过滤XML文件的主要内容,如果未能解决你的问题,请参考以下文章
在Tomcat的安装目录下conf目录下的server.xml文件中增加一个xml代码片段,该代码片段中每个属性的含义与用途