在 PHP 中拆分 XML [英] Split XML in PHP

查看:21
本文介绍了在 PHP 中拆分 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个合并的 xml,其中包含一个根元素和多个项目子元素.像这样

I have a merged xml with a root element and multiple item child elements. Something like this

 <root>
  <item>test1</item>
  <item>test2</item>
 </root>

我想要的是一种解析 xml 并从项目创建 xml 字符串数组的简单方法.

What I want is an easy way to parse the xml and create an array of xml strings from the items.

$arrXml[0] = '<item>test1</item>';
$arrXml[1] = '<item>test2</item>';

我正在寻找一个优雅的解决方案,而不是任何解决方案.

I'm looking for an elegant solution not any solution.

推荐答案

好的,就像在您的问题的评论中已经提到的我不相信这真的是您应该做的,但是由于我受不了 SimpleXml 并且不想让人们认为这是唯一的方法,这是怎么做的

Ok, like already mentioned in the comments to your question I am not convinced this is really what you should be doing, but since I cant stand SimpleXml and dont want people to think it's the only way, here is how to do it

使用 DOM:

$arrXml = array();
$dom    = new DOMDocument;
$dom->loadXML( $xml );
foreach( $dom->getElementsByTagName( 'item' ) as $item ) {
    $arrXml[] = $dom->saveXML( $item );
}
print_r( $arrXml );

<小时>

使用 XMLReader:

$arrXml = array();
$reader = new XmlReader;
$reader->xml( $xml );
while( $reader->read() ) {
    if( $reader->localName === 'item' && $reader->nodeType === 1 ) {
        $arrXml[] = $reader->readOuterXml();
    }
}
print_r( $arrXml );

<小时>

XMLParser*:

xml_parse_into_struct(xml_parser_create(), $xml, $nodes);
$xmlArr = array();
foreach($nodes as $node) {
    if($node['tag'] === 'ITEM') {
        $arrXml[] = "<item>{$node['value']}</item>";
    }
}
print_r($arrXml);

* 这也可以通过在遇到 ITEM 元素时触发的回调来完成.需要更多代码,但非常灵活.

请注意,以上所有内容可能需要根据您的真实 XML 进行一些调整.

鉴于您问题中的 XML(可能只是一个示例)非常简单且定义明确,您还可以使用 explode():

Given that the XML in your question (which is likely only an example) is dirt simple and well defined, you can also use explode():

$arrXml = array_map( 'trim',
    array_filter(
        explode( PHP_EOL, $xml ),
        function( $line ) { return substr( $line, 0, 6 ) === '<item>'; }
));
print_r( $arrXml );

或正则表达式(阅读下面的免责声明)

or a Regex (read disclaimer below)

preg_match_all('#<item>.*</item>#', $xml, $arrXml);
print_r($arrXml[0]);

免责声明 现在,只是为了确保您没有开始定期使用 Regex 或 Explode 解析 XML:最后两种方法仅当您的标记确实像您一样明确定义时才可行展示一下.

Disclaimer Now, just to make sure you are not starting to parse XML with Regex or Explode on a regular basis: The last two approaches are only feasible if your markup is really that clearly defined as you show it.

这篇关于在 PHP 中拆分 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆