Soapbox / laravel-formatter

A Formatter Class for Laravel 4 based on FuelPHP's Formatter Class
249 stars 95 forks source link

How to converting an array to a XML(has attributes) ? #48

Open zishiguo opened 5 years ago

zishiguo commented 5 years ago

If xml likes:

<urlset content_method="full"> 
    <url>
        <loc>http://www.example.com/a.html</loc>
        <desc>a.html</desc>
    </url> 
    <url>
        <loc>http://www.example.com/b.html</loc>
        <desc>b.html</desc>
    </url>
</urlset>

Then, the array is ?

zsping1989 commented 4 years ago
        $data = [
            'urlset' => [
                '@attributes' => [
                    'content_method' => 'full'
                ],
                [
                    '@name' => 'url',
                    'loc' => 'http://www.example.com/a.html',
                    'desc' => 'a.html'
                ], [
                    '@name' => 'url',
                    'loc' => 'http://www.example.com/b.html',
                    'desc' => 'b.html'
                ]
            ]
        ];
        $request_xml = Formatter::make($data, Formatter::ARR)->toXml('xml','utf-8',true);
        dd($request_xml);

结果

<?xml version="1.0" encoding="utf-8"?>
<xml>
    <urlset content_method="full">
        <url>
           <loc>http://www.example.com/a.html</loc>
           <desc>a.html</desc>
       </url> 
       <url>
            <loc>http://www.example.com/b.html</loc>
           <desc>b.html</desc>
       </url>
    </urlset>
</xml>