PHP读取XML文件方法很多,如DOMDocument,simplexml,正则表达式,xmlreader等
这里我们就用DOMDocument即可完成几乎所有常用的读取XML的工作,如属性值和节点值
XML源文件photo.xml格式如下:
folder=”hdpictures/custom/building/”
enable_fullscreen=”true”
drag_speed=”2.4″>
s_building_001.jpg
building (1).jpg
s_building_002.jpg
building (2).jpg
s_building_003.jpg
building (3).jpg
功能需求:读取config下属性folder的值和photo下thumbnail和filename标签值
PHP代码如下:
$doc = new DOMDocument();
$doc->load(‘photo.xml’);
//取得photo和config标签的对象数组
$photos = $doc->getElementsByTagName( “photo” );
$config = $doc->getElementsByTagName( “config” );
$confignode = $config->item(0);
$folder = $confignode->getAttribute(‘folder’);
foreach ($photos as $photo) {
//取得thumbnail的标签的对象数组
$thumbnails = $photo->getElementsByTagName( “thumbnail” );
$filenames = $photo->getElementsByTagName( “filename” );
//取得thumbnail节点中的值
$thumbnail = $thumbnails->item(0)->nodeValue;
$filename = $filenames->item(0)->nodeValue;
echo ‘图片路径:’.$folder.’\n’;
echo ‘缩略图名称:’.$thumbnail.’\n’;
echo ‘大图名称:’.$filename.’\n’;
echo ‘————————-‘;
}