php DOMDocument 创建,加载,解析xml文档代码

作者:袖梨 2022-07-02
 代码如下 复制代码

$xml_str = "";
$xml_str .= "";
$xml_str .= "";
$xml_str .= "harry potter";
$xml_str .= "j.k.rowling";
$xml_str .= "warner bros.";
$xml_str .= "39.0";
$xml_str .= "
";
$xml_str .= "
";

$dom = new domdocument;
$dom->loadxml($xml_str);

echo $dom->savexml();
$dom->save("test.xml");

//domdocument 加载xml文档

$dom = new domdocument;

$dom->load('17-1.xml');
$root = $dom->documentelement;


//解析xml文档

 代码如下 复制代码

$doc = new domdocument();
$doc->load("17-1.xml");

$books = $doc->getelementsbytagname("book");
foreach($books as $book)
{
    $authors = $book->getelementsbytagname("author");
    $author = $authors->item(0)->nodevalue;
   
    $publishers = $book->getelementsbytagname("publisher");
    $publisher = $publishers->item(0)->nodevalue;
   
    $titles = $book->getelementsbytagname("title");
    $title = $titles->item(0)->nodevalue;
   
    $prices = $book->getelementsbytagname("price");
    $price = $prices->item(0)->nodevalue;
   
    echo "$title - $author - $publisher - $price";
    echo "
";
    echo "
";
}

/*
17-1.xml

 代码如下 复制代码


   
        learning php5
        david
        white water press
        29.90
   

   
        learning xml
        jeffson
        white water press
        50.79
   

   
        using perl
        lucas
        white water press
        17.00
   

   
        windows networks
        paul
        white water press
        32.99
   

   
        fly leaf
        jenny
        white water press
        19.50
   


*/
?>

相关文章

精彩推荐