php操作xml文件,xml与array互转

1.SimpleXMLElement

简单轻便,读取,追加,查找,保存:

•SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
•SimpleXMLElement::addChild — Adds a child element to the XML node
•SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
•SimpleXMLElement::attributes — Identifies an element's attributes
•SimpleXMLElement::children — Finds children of given node
•SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
•SimpleXMLElement::count — Counts the children of an element
•SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
•SimpleXMLElement::getName — Gets the name of the XML element
•SimpleXMLElement::getNamespaces — Returns namespaces used in document
•SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query
•SimpleXMLElement::saveXML — 别名 SimpleXMLElement::asXML
•SimpleXMLElement::__toString — Returns the string content
•SimpleXMLElement::xpath — Runs XPath query on XML data

2.DOMDocument

方法更多,可转换成html类型等。

•DOMDocument::__construct — Creates a new DOMDocument object
•DOMDocument::createAttribute — Create new attribute
•DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
•DOMDocument::createCDATASection — Create new cdata node
•DOMDocument::createComment — Create new comment node
•DOMDocument::createDocumentFragment — Create new document fragment
•DOMDocument::createElement — Create new element node
•DOMDocument::createElementNS — Create new element node with an associated namespace
•DOMDocument::createEntityReference — Create new entity reference node
•DOMDocument::createProcessingInstruction — Creates new PI node
•DOMDocument::createTextNode — Create new text node
•DOMDocument::getElementById — Searches for an element with a certain id
•DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
•DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
•DOMDocument::importNode — Import node into current document
•DOMDocument::load — Load XML from a file
•DOMDocument::loadHTML — Load HTML from a string
•DOMDocument::loadHTMLFile — Load HTML from a file
•DOMDocument::loadXML — Load XML from a string
•DOMDocument::normalizeDocument — Normalizes the document
•DOMDocument::registerNodeClass — Register extended class used to create base node type
•DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
•DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
•DOMDocument::save — Dumps the internal XML tree back into a file
•DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
•DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
•DOMDocument::saveXML — Dumps the internal XML tree back into a string
•DOMDocument::schemaValidate — Validates a document based on a schema
•DOMDocument::schemaValidateSource — Validates a document based on a schema
•DOMDocument::validate — Validates the document based on its DTD
•DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object
美化xml格式:
<?php
$xml = simplexml_load_file('example.xml'); //读取 XML数据
echo $xml->asXML(); //标准化 XML数据
DOMDocument 追加节点
<?php

$doc = new DOMDocument('1.0', 'UTF-8');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Saving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Saving only the title part:\n";
echo $doc->saveXML($title);

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XML:
http://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress

xml与Array互转:

<?php
//数组转XML
function arrayToXml($data, &$xml_data) {
    foreach ($data as $key => $value) {
        if (is_numeric($key)) {
            $key = 'item' . $key; //dealing with <0/>..<n/> issues
        }
        if (is_array($value)) {
            $subnode = $xml_data->addChild($key);
            arrayToXml($value, $subnode);
        } else {
            $xml_data->addChild("$key", htmlspecialchars("$value"));
        }
    }
}

function array2Xml($array, $rootElement = null, $xml = null) {
    // If there is no Root Element then insert root
    $version = '<?xml version="1.0" encoding="UTF-8"?>';
    $rootElement = $version . (empty($rootElement) ? '<root/>' : $rootElement);
    if ($xml === null) {
        $xml = new SimpleXMLElement($rootElement);
    }

    // Visit all key value pair
    foreach ($array as $k => $v) {
        // If there is nested array then
        if (is_array($v)) {
            // Call function for nested array
            array2Xml($v, $k, $xml->addChild($k));
        } else {
            // Simply add child element.
            $xml->addChild($k, $v);
        }
    }
    return $xml->asXML();
}

//将XML转为array
function xmlToArray($xml) {
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}

$arr = ['name' => '阳水平', 'age' => 12, 'cc' => ['web' => 'nbfu.com', 'code' => 'nbfu.code', 'dd' => ['aa' => 'aaa.com']]];
// creating object of SimpleXMLElement
$xml_data = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><data></data>');
// function call to convert array to xml
arrayToXml($arr, $xml_data);
$xml_string = $xml_data->asXML();
print_r($xml_string);

// xml to array marked by yangshuiping
print_r(xmlToArray($xml_string));

// 第二种放方法 marked by yangshuiping
print_r(array2Xml($arr));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SHUIPING_YANG

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值