PHP如何读XML(刚学PHP,请大家帮一下)
我现在的配置是 centos5.3 php 5.2.5 在读xml时,总不成功,代码如下:
<?php
echo "start";
// 首先要建一个DOMDocument对象
try {
$xml = new DOMDocument("1.0");
// 加载Xml文件
$xml->load("me.xml");
// 获取所有的post标签
$postDom = $xml->getElementsByTagName("post");
// 循环遍历post标签
foreach($postDom as $post){
// 获取Title标签Node
$title = $post->getElementsByTagName("title");
/**
* 要获取Title标签的Id属性要分两部走
* 1. 获取title中所有属性的列表也就是$title->item(0)->attributes
* 2. 获取title中id的属性,因为其在第一位所以用item(0)
*
* 小提示:
* 若取属性的值可以用item(*)->nodeValue
* 若取属性的标签可以用item(*)->nodeName
* 若取属性的类型可以用item(*)->nodeType
*/
echo "Id: " . $title->item(0)->attributes->item(0)->nodeValue . "<br />";
echo "Title: " . $title->item(0)->nodeValue . "<br />";
echo "Details: " . $post->getElementsByTagName("details")->item(0)->nodeValue . "<br /><br />";
}
}
catch (Exception $e) {
print $e->getMessage();
exit();
}
echo "end";
?>
/////////////////
出错提示为:
X-Powered-By: PHP/5.2.5
Set-Cookie: ZendDebuggerCookie=127.0.0.1%3A10137%3A0||084|77742D65|1013; path=/
Content-type: text/html
start<br />
<b>Warning</b>: DOMDocument::load() [<a href='function.DOMDocument-load'>function.DOMDocument-load</a>]: Start tag expected, '<' not found in /var/www/html/TestXML/me.xml, line: 1 in <b>/var/www/html/TestXML/index.php</b> on line <b>9</b><br />
end
////////////////////////
me.xml:
<?xml version="1.0" eccoding="utf-8"?>]
<phplamp>
<post>
<title id="1">php dfs fd </title>
<details> 详细内容</details>
</post>
<post>
<title id="2">php dfs fd </title>
<details> 详细内容2</details>
</post>
</phplamp>