回显xml字符串的特定部分

时间:2017-08-02 10:23:21

标签: php xml

假设我有以下xml:

<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <id>1</id>
        <name>Apple iPhone 7</name>
    </product>
    <product>
        <id>2</id>
        <name>Samsung Galaxy S7</name>
    </product>
</products>

使用以下代码,我可以打印整个xml-string:

$xml = simplexml_load_string($string);

echo '<pre>'.htmlentities($xml->asXML()).'</pre>';

我现在正在寻找代码来回应xml字符串的 特定部分 ,假设产品[0]。

我希望能够按如下方式回应:

<product>
    <id>1</id>
    <name>Apple iPhone 7</name>
</product>

任何人都知道解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以使用此功能:

<?php
    function xml2ary(&$string) {
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parse_into_struct($parser, $string, $vals, $index);
        xml_parser_free($parser);
        $mnary=array();
        $ary=&$mnary;
        foreach ($vals as $r) {
            $t=$r['tag'];
            if ($r['type']=='open') {
                if (isset($ary[$t])) {
                    if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
                    $cv=&$ary[$t][count($ary[$t])-1];
                } else $cv=&$ary[$t];
                if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
                $cv['_c']=array();
                $cv['_c']['_p']=&$ary;
                $ary=&$cv['_c'];
            } elseif ($r['type']=='complete') {
                if (isset($ary[$t])) { // same as open
                    if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
                    $cv=&$ary[$t][count($ary[$t])-1];
                } else $cv=&$ary[$t];
                if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
                $cv['_v']=(isset($r['value']) ? $r['value'] : '');
            } elseif ($r['type']=='close') {
                $ary=&$ary['_p'];
            }
        }    

        _del_p($mnary);
        return $mnary;
    }
    // _Internal: Remove recursion in result array
    function _del_p(&$ary) {
        foreach ($ary as $k=>$v) {
            if ($k==='_p') unset($ary[$k]);
            elseif (is_array($ary[$k])) _del_p($ary[$k]);
        }
    }

    $string = '<?xml version="1.0" encoding="UTF-8"?>
        <products>
            <product>
                <id>1</id>
                <name>Apple iPhone 7</name>
            </product>
        <product>
            <id>2</id>
            <name>Samsung Galaxy S7</name>
        </product>
    </products>';

    $requeststring = xml2ary($string);

    echo $requeststring["products"]["_c"]["product"][0]["_c"]["id"]["_v"]; //outputs 1

?>

只需更改[“产品”]或[“产品”]或[“id”]即可获得自己的结果。