php php解析xml字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3630866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:29:14  来源:igfitidea点击:

php parse xml string

phpxml

提问by salmane

Possible Duplicate:
Best XML Parser for PHP

可能的重复:
PHP 的最佳 XML 解析器

I have a string with XML data in it. How do I parse it in PHP?

我有一个包含 XML 数据的字符串。我如何在 PHP 中解析它?

thank you

谢谢你

回答by aularon

Try with simple XML, here's an example:

尝试使用简单的 XML,这是一个示例:

do.php:

做.php:

<?php
$xml_str = file_get_contents('xmlfile.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('*/item');

foreach($items as $item) {
    echo $item['title'], ': ', $item['description'], "\n";
}

xmlfile.xml:

xmlfile.xml:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <items>
        <item title="Hello World" description="Hellowing the world.." />
        <item title="Hello People" description="greeting people.." />
    </items>
</xml>

回答by NexusRex

For those situations where SimpleXML is not available, I use this function originally posted in a comment on php.net. It works great 99% of the time.

对于那些 SimpleXML 不可用的情况,我使用最初发布在 php.net 上的评论中的这个函数。它在 99% 的情况下都很好用。

<?php
/**
 * Convert XML to an Array
 *
 * @param string  $XML
 * @return array
 */
function XMLtoArray($XML)
{
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $XML, $vals);
    xml_parser_free($xml_parser);
    // wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
    $_tmp='';
    foreach ($vals as $xml_elem) {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_level!=1 && $x_type == 'close') {
            if (isset($multi_key[$x_tag][$x_level]))
                $multi_key[$x_tag][$x_level]=1;
            else
                $multi_key[$x_tag][$x_level]=0;
        }
        if ($x_level!=1 && $x_type == 'complete') {
            if ($_tmp==$x_tag)
                $multi_key[$x_tag][$x_level]=1;
            $_tmp=$x_tag;
        }
    }
    // jedziemy po tablicy
    foreach ($vals as $xml_elem) {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_type == 'open')
            $level[$x_level] = $x_tag;
        $start_level = 1;
        $php_stmt = '$xml_array';
        if ($x_type=='close' && $x_level!=1)
            $multi_key[$x_tag][$x_level]++;
        while ($start_level < $x_level) {
            $php_stmt .= '[$level['.$start_level.']]';
            if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
                $php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
            $start_level++;
        }
        $add='';
        if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete')) {
            if (!isset($multi_key2[$x_tag][$x_level]))
                $multi_key2[$x_tag][$x_level]=0;
            else
                $multi_key2[$x_tag][$x_level]++;
            $add='['.$multi_key2[$x_tag][$x_level].']';
        }
        if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes', $xml_elem)) {
            if ($x_type == 'open')
                $php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
            else
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
            eval($php_stmt_main);
        }
        if (array_key_exists('attributes', $xml_elem)) {
            if (isset($xml_elem['value'])) {
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
                eval($php_stmt_main);
            }
            foreach ($xml_elem['attributes'] as $key=>$value) {
                $php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
                eval($php_stmt_att);
            }
        }
    }
    return $xml_array;
}
?>

回答by chim

If you're familiar with the Zend Framework, pass your XML to Zend_Config_Xml

如果您熟悉 Zend 框架,请将您的 XML 传递给 Zend_Config_Xml

given xml like this

给定这样的 xml

$myXml = '
<?xml version="1.0" ?>
<top>
  <var>value</var>
  <nested>
    <var>value</var>
  </nested>
  <arrayVar>
    <item>1</item>
    <item>2</item>
    <item>3</item>        
  </arrayVar>
</top>';

You can access it thusly:

您可以这样访问它:

$xml = new Zend_Config_Xml( $myXml );

$var = $xml->var;
$nestedVar = $xml->nested->var;
$arrayVar = $xml->arrayVar->toArray();

Zend Config XML uses simplexml and builds on this to give a nice interface, that makes it really easy to get to the xml node you're looking for.

Zend Config XML 使用 simplexml 并以此为基础提供了一个漂亮的界面,这使得访问您正在寻找的 xml 节点变得非常容易。

There's loads more in the ZF Manual, including how to access attributes, and some other really useful features.

ZF 手册中有更多内容,包括如何访问属性以及其他一些非常有用的功能。

http://framework.zend.com/manual/en/zend.config.adapters.xml.html

http://framework.zend.com/manual/en/zend.config.adapters.xml.html

Zend Config is one of the easiest to use parts of ZF, and (I think) it's a standalone component, you can use just Zend Config and no other part of ZF

Zend Config 是 ZF 中最容易使用的部分之一,并且(我认为)它是一个独立的组件,您可以只使用 Zend Config 而不能使用 ZF 的其他部分