PHP操作XML

释放双眼,带上耳机,听听看~!

1 读取XML

<?php
    $xml=new DOMDocument('1.0','UTF-8');
    //加载Xml文件
    $xml->load('test.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 />';
    }
?>

2 生成XML

<?php //    $books = array(); //    $books [] = array( //      'title' => 'PHP Hacks', //      'author' => 'Jack Herrington', //      'publisher' => "O'Reilly" //    ); //      $books [] = array( //      'title' => 'Podcasting Hacks', //      'author' => 'Jack Herrington', //      'publisher' => "O'Reilly" //      ); // //      $doc = new DOMDocument(); //      $doc->formatOutput = true; // //      $r = $doc->createElement( "books" ); //      $doc->appendChild( $r ); // //     foreach( $books as $book ) //     { //      $b = $doc->createElement( "book" ); //      //      $author = $doc->createElement( "author" ); //      $author->appendChild( //      $doc->createTextNode( $book['author'] ) //     ); //     $b->appendChild( $author ); // //  $title = $doc->createElement( "title" ); //  $title->appendChild( //  $doc->createTextNode( $book['title'] ) //  ); //  $b->appendChild( $title ); // //  $publisher = $doc->createElement( "publisher" ); //  $publisher->appendChild( //  $doc->createTextNode( $book['publisher'] ) //  ); //  $b->appendChild( $publisher ); // //  $r->appendChild( $b ); //  } //  //  header("Content-Type:text/xml"); //  echo $doc->saveXML();     $dom=new DOMDocument("1.0",'UTF-8');         header("Content-Type:text/plain");         $root=$dom->createElement( "toppings" );         $dom->appendChild( $root );         $item=$dom->createElement( "item" );         $root->appendChild( $item );         $text=$dom->createTextNode("pepperoni");     $item->appendChild( $text );         //属性     $price=$dom->createAttribute("price");     $item->appendChild( $price );         $priceValue=$dom->createTextNode("4");     $price->appendChild( $priceValue );             echo $dom->saveXML();     ?>

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++遍历文件夹

2022-1-11 12:36:11

安全漏洞

PHP 7.0.14 发布,修复安全漏洞

2016-12-9 11:12:22

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索