php dom方式解析 创建xml

<?xml version="1.0" encoding="UTF-8"?>
<notes>
	<note>
		<to>George</to>
		<from>John</from>
		<heading>Reminder</heading>
		<body>Don't forget the meeting!</body>
	</note>
	<note>
		<to>George2</to>
		<from>John2</from>
		<heading>Reminder2</heading>
		<body>Don't forget the meeting!2</body>
	</note>
	<instances>
		<instance st="192.168.234.121" />
		<instance st="192.168.234.28" />
	</instances>
</notes>

<?php

function parse1()
{
    $xmlDoc = new DOMDocument();
    $xmlDoc->load("test.xml");
    $x = $xmlDoc->documentElement;
    
    foreach ($x->childNodes as $item) {
        print $item->nodeName . " = " . $item->nodeValue . "<br />";
//         if ($item->hasAttribute("st")) {
//             print($item->getAttribute("st"));
//         }
    }
    echo "-------------------\n";
    $note = $xmlDoc->getElementsByTagName("note");
    foreach ($note as $item1) {
        var_dump($item1); // DOMElement
        $to = $item1->getElementsByTagName("to");
        var_dump($to); // DOMNodeList
        var_dump($to->item(0)->nodeValue);
        echo "-------------------\n";
    }
    $note = $xmlDoc->getElementsByTagName("instance");
    foreach ($note as $item1) {
        var_dump($item1); // DOMElement
        
        echo $item1->getAttribute("st");
        echo "-------------------\n";
    }
}

function create()
{
    $xmDoc = new DOMDocument("1.0", "utf-8");
    $a = $xmDoc->createElement("a");
    $text = $xmDoc->createTextNode("text");
    $b = $xmDoc->createElement("ab", "ab");
    $a->appendChild($b);
    $a->setAttribute("attr", "attr");
    $xmDoc->appendChild($a);
    echo $xmDoc->saveXML();
}
parse1();
?>



















没有更多推荐了,返回首页