【www.gdgbn.com--php入门】

明确目标: 1、理解xml的结构;2、如何动态建立xml文件;3、如何读取和修改xml文件

  一、 xml的结构是树形结构:

这个好理解。简单写一个:

 1 2   3      1 4      pic 1 5   6   7      2 8      pic 2 9   10   11      312      pic 313   14 
 

 

  二、我使用的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"));

     现在内存中应该是这样的: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");

      这种方法有点麻烦,参考文件:http://wenku.baidu.com/view/8f0c3c5177232f60ddcca163.html

    不过有一种我喜欢的方法: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()输出不准确

本文来源:http://www.gdgbn.com/jiaocheng/28668/