Parsing XML using PHP

后端 未结 8 2202
日久生厌
日久生厌 2020-12-12 02:16

I\'ve consistently had an issue with parsing XML with PHP and not really found \"the right way\" or at least a standardised way of parsing XML files.

Firstly i\'m tr

8条回答
  •  眼角桃花
    2020-12-12 02:35

    This was how i have eventually done it using XMLReader:

    ";
    
    $items = array ();
    $i = 0;
    
    $xmlReader = new XMLReader();
    $xmlReader->open(XMLFILE, null, LIBXML_NOBLANKS);
    
    $isParserActive = false;
    $simpleNodeTypes = array ("title", "description", "media:title", "link", "author", "pubDate", "guid");
    
    while ($xmlReader->read ())
    {
        $nodeType = $xmlReader->nodeType;
    
        // Only deal with Beginning/Ending Tags
        if ($nodeType != XMLReader::ELEMENT && $nodeType != XMLReader::END_ELEMENT) { continue; }
        else if ($xmlReader->name == "item") {
            if (($nodeType == XMLReader::END_ELEMENT) && $isParserActive) { $i++; }
            $isParserActive = ($nodeType != XMLReader::END_ELEMENT);
        }
    
        if (!$isParserActive || $nodeType == XMLReader::END_ELEMENT) { continue; }
    
        $name = $xmlReader->name;
    
        if (in_array ($name, $simpleNodeTypes)) {
            // Skip to the text node
            $xmlReader->read ();
            $items[$i][$name] = $xmlReader->value;
        } else if ($name == "media:thumbnail") {
            $items[$i]['media:thumbnail'] = array (
                    "url" => $xmlReader->getAttribute("url"),
                    "width" => $xmlReader->getAttribute("width"),
                    "height" => $xmlReader->getAttribute("height"),
                    "type" => $xmlReader->getAttribute("type")
            );
        } else if ($name == "media:content") {
            $items[$i]['media:content'] = array (
                    "url" => $xmlReader->getAttribute("url"),
                    "width" => $xmlReader->getAttribute("width"),
                    "height" => $xmlReader->getAttribute("height"),
                    "filesize" => $xmlReader->getAttribute("fileSize"),
                    "expression" => $xmlReader->getAttribute("expression")
            );
        }
    }
    
    print_r($items);
    echo "
    "; ?>

提交回复
热议问题