How do I create variables from XML data in PHP?

后端 未结 9 1585
不思量自难忘°
不思量自难忘° 2021-01-25 18:34

Been trying to figure this out for a short while now but having now luck, for example I have an external xml document like this:


&         


        
相关标签:
9条回答
  • 2021-01-25 19:12

    why not doing the array directly?

    var positions = document.getElementsByTagName("positions");
    var positions_final_arr = [];
    for(int i = 0; i < positions.length; i++){
        positions_final_arr[i] = [];
        var inner_pos = positions[i].getElementsbyTagName("position");
        for(int l = 0; l < inner_pos.length; l++){
            positions_final_arr[i][l] = inner_pos[i].value;
        }
    }
    console.log(positions_final_arr);
    
    0 讨论(0)
  • 2021-01-25 19:13

    The simplest method is to use SimpleXML:

    $xml = simplexml_load_string(... your xml here...);
    
    $values = array()
    foreach($xml->positions as $pos) {
       $values[$pos] = $pos;
    }
    

    You do not want to auto-create variables in the manner you suggest - it litters your variable name space with garbage. Consider what happens if someone sends over an XML snippet which has <position>_SERVER</position> and you create a variable of that name - there goes your $_SERVER superglobal.

    0 讨论(0)
  • 2021-01-25 19:20
    <?php
    $xmlUrl = "feed.xml"; // XML feed file/URL
    $xmlStr = file_get_contents($xmlUrl);
    $xmlObj = simplexml_load_string($xmlStr);
    $arrXml = json_decode(json_encode($xmlObj), true); # the magic!!!
    print_r($arrXml);
    ?>
    

    This will give the following result:

    Array
    (
        [name] => My Template Name
        [author] => John Doe
        [positions] => Array
            (
                [position] => Array
                    (
                        [0] => top-a
                        [1] => top-b
                        [2] => sidebar-a
                        [3] => footer-a
                    )
    
            )
    
    )
    
    0 讨论(0)
提交回复
热议问题