laravel将XML转成对象或者数组

Song4187 次浏览0个评论2017年09月17日

有很多时候我们使用Laravl获取接口或者读取数据时,常常会返回XML数据,今天我们来说说laravel将XML转成对象或者数组,希望大家能够受到启发。

一、使用PH将xml转成数组

1、PHP将xml字符串转换为数组

如果你是通过curl等http请求获取的xml数据,你可以使用PHP中的simplexml_load_string()函数把XML数据载入对象中。如果失败,则返回 false。这里我们测试使用laravel的GUZZLE发送CURL请求:

// 构建GUZZLE请求
$client = new Client();
// 请求中国天气网获取数据
$response = $client->request('GET',"http://wthrcdn.etouch.cn/WeatherApi?citykey=101010100");
// 获取头部信息
$header = $response->getHeaders();
// 获取html
$body = $response->getBody();
$xml = simplexml_load_string($body);
dump($xml);
echo $xml->city;

你会发现返回一个SimpleXMLElement对象,你可以直接$xml->city实例化得到数据;如果你想将数据从对象转数组,只需要使用get_object_vars()函数即可。

# 将XML转换为对象
$obj=simplexml_load_string($body,'SimpleXMLElement',LIBXML_NOCDATA);
# 将对象转换为数组
$array = get_object_vars($obj);

laravel将XML转成对象或者数组

2、PHP将xml文件换为数组

如果你是获取XML文件转化为数组,你可以使用simplexml_load_file()函数把XML数据载入对象中。如果失败,则返回 false。

# 将XML文件转换为对象
$xml = simplexml_load_file('test.xml');
# 将对象转换为数组
$array = get_object_vars($obj);

二、使用Laravel拓展xml转成数组

其实我们直接使用方案一中的方法即可,如果你想使用Laravel拓展讲XML转数组,你可以使用xml-transform拓展。

1、安装

使用composer安装即可:

composer require cdekok/xml-transform
2、数据列表
// Optional add namespaces in the XML
$namespaces = ['oai' => 'http://www.openarchives.org/OAI/2.0/'];

// Define the mapping for the array that you want to have filled
$mapping = [
    'id' => [
        'xpath' => './/oai:identifier/text()'
    ],
    'material' => [
        'xpath' => './/oai:material/text()',
        'repeatable' => true // If elements are repeatable set this option so an array will be returned
    ],
];

$data = (new \XmlTransform\Mapper($mapping, '//oai:OAI-PMH/oai:ListRecords/oai:record', $namespaces))
    ->from('somefile.xml')
    ->transform();

// $data will contain something like
[
    ['id' => '12', 'material' => ['paint', 'pencil']],
    ['id' => '13', 'material' => ['pen', 'pencil']],
]
3、单一数组

为了方便也可以只映射到1而不是一个结果列表的数组。

$data = (new \XmlTransform\Mapper($mapping, '//oai:OAI-PMH/oai:ListRecords/oai:record', $namespaces))
    ->from('somefile.xml')
    ->transformOne();

// $data will contain something like
['id' => '12', 'material' => ['paint', 'pencil']]
4、重复嵌套元素
$mapping = [
    'id' => ['xpath' => './/oai:objectid/text()'],
    'creator' => [
        'repeatable' => true, // Mark the element as repeatable
        'context' => './/oai:constituent', // new context for the nested elements
        'values' => [
            'name' => ['xpath' => './/text()'],
            'death_date' => ['xpath' => './/@death_date'],
        ]
    ]
];

$transformer = new \XmlTransform\Mapper($mapping, '//oai:record', $namespaces);
$result = $transformer->from($xml)->transformOne();

// Result will contain something like this
[
    'id' => '3517',
    'creator' => [
        ['name' => 'Rembrandt', 'death_date' => '1669'],
        ['name' => 'Johannes Mock', 'death_date' => '1884'],
        ['name' => 'Georg Friedrich Schmidt', 'death_date' => '1775'],
    ]
]

5、XML文件

从返回数组中过滤空值。

可选元素(上下文) 如果有可选的元素与上下文在XML你需要启用可选设置防止contextnotfoundexception

$mapping = [
    'record' => [
        'context' => './/data',
        'values' => [
            'title' => ['xpath' => './/title/text()'],
            'creator' => ['xpath' => './/creator/text()'], // optional
        ]
    ],
];

$transformer = new \XmlTransform\Mapper($mapping, '//record');
$result = $transformer->from($xml)->optionalElements()->filter()->transform();

// Result creator is missing.
[
    'record' => [
        'title' => 'test',
        'creator' => 'Bert',
    ],
],
[
    'record' => [
        'title' => 'test 2',
    ]
]

提交评论

请登录后评论

用户评论

    当前暂无评价,快来发表您的观点吧...

更多相关好文

    当前暂无更多相关好文推荐...