XML文档中第一个节点之前的字符串

时间:2015-01-11 08:26:38

标签: php xml string parsing document

我对XML解析有一个奇怪的问题 PHP:

/**
 * Klasa zamiany pliku XML na tablice w PHP
 * Dodałem metode statyczną utf8_for_xml która usuwa krzaki bezpośrednio przy pobieraniu XML'a
 * 
 * XML2Array: A class to convert XML to array in PHP
 *
 * Author : Abdelwahd Hannabou
 *
 * Usage:
 *       $Array = XML2Array::CreateArray('FILE_PATH');
 */

class XML2Array
{
    public static function utf8_for_xml($string)
    {
        return preg_replace ('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $string);
    }

    public static function ampersandClean($string)
    {
       return preg_replace('/&/', '&', $string);
    }

    public static function CreateArray($XmlFilePath)
    {
        if (!file_exists($XmlFilePath)) {
            echo "Wrong path";
            return FALSE;
        }
        $Class = array();
        $Class['UsersFileXml'] = self::ampersandClean(self::utf8_for_xml(file_get_contents($XmlFilePath)));
/*      echo "<pre>";
        print_r($Class['UsersFileXml']);
        echo "</pre>"; */

        $Class['FileXml'] = simplexml_load_string($Class['UsersFileXml']);
        echo "<pre>";
        print_r($Class['FileXml']);
        echo "</pre>";
        $Class['FileJson'] = json_encode($Class['FileXml']);
        $Array = json_decode($Class['FileJson'],TRUE);
        unset($Class);

        return $Array;
    }
}

$xml = XML2Array::CreateArray('p.xml');
/* echo '<pre>';
print_r($xml);
echo '</pre>';
 */

XML p.xml:

<?xml version="1.0" encoding="UTF-8"?>
<main>
<wezel1>test</wezel1>
<wezel2>test2</wezel2>
<something>string so array did not show this what is in "somethingelse"<somethingelse>test3</somethingelse></something>
</main>

问题是数组中没有显示节点<somethingelse>test3</somethingelse>。如何跳过此字符串并解析下一个节点?当字符串不在第一个位置时,它就可以了:

itwork.xml

<?xml version="1.0" encoding="UTF-8"?>
<main>
<wezel1>test</wezel1>
<wezel2>test2</wezel2>
<something><somethingelse>test3</somethingelse>String but here string is not problem, PHP parse next node<itisok>This is in array</itisok></something>
</main>

1 个答案:

答案 0 :(得分:-1)

这可能不是您正在寻找的答案,但它是正确的答案。不要重新发明轮子PHP already handled this 检查第一条评论 - 我将为您省去麻烦: 三行xml2array:

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);