How do I create variables from XML data in PHP?

2020-04-18 04:59发布

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>
    <positions>
        <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.

标签: php xml
9条回答
唯我独甜
2楼-- · 2020-04-18 05:20

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.

查看更多
男人必须洒脱
3楼-- · 2020-04-18 05:22

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
                )

        )

)
查看更多
放荡不羁爱自由
4楼-- · 2020-04-18 05:26

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);
查看更多
欢心
5楼-- · 2020-04-18 05:27

$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);
查看更多
混吃等死
6楼-- · 2020-04-18 05:31

You want the built in class Simplexml

查看更多
狗以群分
7楼-- · 2020-04-18 05:35
$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

查看更多
登录 后发表回答