开发者

How do I create variables from XML data in PHP?

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:

<?xml version="1.0" ?>
<template>
    <name>My Template Name</name>
    <author>John Doe</author>
    <positio开发者_开发问答ns>
        <position>top-a</position>
        <position>top-b</position>
        <position>sidebar-a</position>
        <position>footer-a</position>
    </positions>
</template>

How can I process this document to create variables like this:

$top-a = top-a;
$top-b = top-b;
$sidebar-a = sidebar-a;
$footer-a = footer-a

If you can't make them into variables, how would you put them into an array?

Any help will be greatly appreciated.


From the PHP web site at http://www.php.net/manual/en/function.xml-parse.php:

Ashok dot 893 at gmail dot com 26-Apr-2010 05:52 This is very simple way to convert all applicable objects into associative array. This works with not only SimpleXML but any kind of object. The input can be either array or object. This function also takes an options parameter as array of indices to be excluded in the return array. And keep in mind, this returns only the array of non-static and accessible variables of the object since using the function get_object_vars().

<?php
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
    $arrData = array();

    // if input is object, convert into array
    if (is_object($arrObjData)) {
        $arrObjData = get_object_vars($arrObjData);
    }

    if (is_array($arrObjData)) {
        foreach ($arrObjData as $index => $value) {
            if (is_object($value) || is_array($value)) {
                $value = objectsIntoArray($value, $arrSkipIndices); // recursive call
            }
            if (in_array($index, $arrSkipIndices)) {
                continue;
            }
            $arrData[$index] = $value;
        }
    }
    return $arrData;
}
?>

Usage:

<?php
$xmlUrl = "feed.xml"; // XML feed file/URL
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
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
                )

        )

)


You want the built in class Simplexml


Take a look at SimpleXML:

http://www.php.net/manual/en/simplexml.examples-basic.php

It parses XML into a "map-like" structure which you could then use to access your content. For your particular case,

$xml = new SimpleXMLElement($xmlstr);

$top_a =  $xml->template->positions[0] 


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.


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);


$str = "your xml";

$xml = simplexml_load_string($str);
$result = array();
foreach ($xml->positions as $pos) {
    foreach ($pos->position as $p) {
        $element = (string)$p[0];
        $result[$element] = $element;
    }
}

var_dump($result);


Use SimpleXML to parse the file into an object/array structure, then simply use list:

$sxml = new SimpleXMLElement($xml);
$positions = (array)$sxml->positions->children();
list($top_a, $top_b, $sidebar_a, $footer_a) = $positions['position'];


$dom = new DOMDocument;
    $dom->loadXML('<root><position>a</position></root>'); //your string here 
    //$dom->loadXML(file_get_contents($file_with_pxml)); - from file
    $position = $dom->getElementsByTagName('position');
    for ($i=0; $i<$position->length; $i++)
    {
      $item = $position->item($i);
      ${$item->nodeValue} = $item->nodeValue;//$$item->nodeValue = $item->nodeValue;
    }

But as I know - you can't create variable with dash in name in PHP


<?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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜