php xml 入门学习资料
发布时间:2020-05-24 20:35:10 所属栏目:PHP 来源:互联网
导读:今天做项目时遇到一个问题:需要动态更新主页上的图片,以示本站不是做完了就算了,是有人一直在维护。好了,需求有了,如何实现?!
起因: 一、 xml的结构是树形结构: 这个好理解。简单写一个: <div class="codetitle"><a style="CURSOR: pointer" data="738" class="copybut" id="copybut738" onclick="doCopy('code738')"> 代码如下:<div class="codebody" id="code738"> 二、我使用的php创建:1. 定义一个DOM对象: $dom = new DomDocument('1.0'); 2. 添加子元素:$dom->appendChild($dom->createElement("pictures")) 内存中的原型是: 继续往里边加子元素:->appendChild($dom->createElement("picture")); 继续加: ->appendChild($dom->createElement("id")); 不加子元素了,加节点: ->appendChild($dom->createNode("1")) 上面的*代表上上一行的代码;这样一来就可以写成一行: $dom->appendChild($dom->createElement("pictures"))->appendChild($dom->createElement("picture")) ->appendChild($dom->createElement("id"))->appendChild($dom->createNode("1")); 现在内存中应该是这样的: 显然里要求还远,很容易看懵的。 因此一般这么写: $pictures = $dom->appendChild($dom->createElement("pictures")); $picture = $pictures->appendChild($dom->createElement("picture")); $id = $picture->appendChild($dom->createElement("id")); $id->appendChild($dom->createNode("1")); 下面还可以接着创建name节点: $name = $picture->appendChild($dom->createElement("name")); $name->appendChild($dom->createNode("pic 1")); 接下来还要接着创建picture节点: $picture = $pictures->appendChild($dom->createElement("picture")); 其实这些麻烦的事可以写个for循环来实现。 生成xml文件: $dom->formatOutput = true;//设置格式化输出 $dom->save("erhsh.xml");//保存xml文件 三、读取xml文件。 1、还是定义一个DOM对象;$dom->new DomDocument(); 2、加载xml文件:$dom->load("erhsh.xml"); 3、按照节点的名字取得节点集合:$dom->getElementByTagName("pictures"); 这种方法有点麻烦,参考文件: //www.jb51.cc/article/25853.htm 不过有一种我喜欢的方法:simplexml_load_file("erhsh.xml"); 此方法可以把xml文件的内容转换成对象的形式,使用"->"结和"[]"很容易去的xml的内容; 但是在开发中还是遇到了一点问题: 当执行:print_r($xml->pictures);时输出的是一个 SimpleXMLElement 对象,([picture] => array([0]=>array(...)[1]=>array(...))); 再执行:print_r($xml->pictures->picture);输出的是n个分开的对象。 执行:print_r($xml->pictures->picture[0]->id);输出的还是一个对象。这就很不理解,应该是一个字符串。 最后网上说是“迭代对象”, 应该使用echo输出,print_r(), var_dump()输出不准确。参考地址://www.jb51.cc/article/25852.htm 当然也可以修改xml的值通过这个方法。 写的很烂,仅供本人备忘。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |