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:36

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'];
查看更多
3楼-- · 2020-04-18 05:36
<?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
                )

        )

)
查看更多
欢心
4楼-- · 2020-04-18 05:42

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] 
查看更多
登录 后发表回答