通过PHP读取XML并将SimpleXMLElement对象转换为数组

时间:2017-05-16 13:14:58

标签: php xml

我的XML文件内容如下:

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:x2="http://schemas.microsoft.com/office/excel/2003/xml" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:html="http://www.w3.org/TR/REC-html40" xmlns:c="urn:schemas-microsoft-com:office:component:spreadsheet">
    <OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"></OfficeDocumentSettings>
    <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"></ExcelWorkbook>
    <Worksheet ss:Name="Sheet 1">
        <Table>
            <Row>
                <Cell>
                    <Data ss:Type="String">store</Data>
                </Cell>
                <Cell>
                    <Data ss:Type="String">websites</Data>
                </Cell>
                <Cell>
                    <Data ss:Type="String">attribute_set</Data>
                </Cell>
                <Cell>
                    <Data ss:Type="String">type</Data>
                </Cell>
                <Cell>
                    <Data ss:Type="String">category_ids</Data>
                </Cell>
            </Row>
            <Row>
                <Cell>
                    <Data ss:Type="String">admin</Data>
                </Cell>
                <Cell>
                    <Data ss:Type="String">base</Data>
                </Cell>
                <Cell>
                    <Data ss:Type="String">Books</Data>
                </Cell>
                <Cell>
                    <Data ss:Type="String">simple</Data>
                </Cell>
                <Cell>
                    <Data ss:Type="String">2,4,276,280</Data>
                </Cell>
            </row>
        </Table>
    </Worksheet>
</Workbook>

我必须将每一行转换为数组元素。为此我正在使用:

$xml = simplexml_load_file('list_product.xml');

我能够获得行数组但是对于单元格我只获得SimpleXMLElement个对象。

2 个答案:

答案 0 :(得分:0)

使用这样的简单函数:

$output = null;
function simpleXmlElementToArray(&$output, \SimpleXmlElement $element)
{
    $output = (array)$element;
    foreach ($output as $k => $v) {
        if ($v instanceof \SimpleXMLElement) {
            simpleXmlElementToArray($output[$k], $v);
        }
    }
}

答案 1 :(得分:0)

df.dplyr.purrr <- listOfDataFrames %>% map_df(bind_rows)