DIGITAL4FRONT / CODE BASE

How to Parse Excel XML Files with PHP SimpleXML and Namespaces

Learn how to read Excel 2003 SpreadsheetML XML files using PHP SimpleXML. Handle XML namespaces, extract worksheet rows, preserve column positions with ss:Index, account for merged cells and convert spreadsheet data into structured PHP arrays.

Share

Excel 2003 XML files can be parsed using PHP's SimpleXML extension, but the XML namespaces and spreadsheet-specific attributes require special handling. The simplest approach is to register the spreadsheet namespace, locate worksheet rows using XPath and extract individual cells while preserving their column positions. This avoids unnecessarily complicated nested loops and prevents incorrect data extraction when cells are missing or merged.

Why SimpleXML cannot find your worksheet data

Consider an Excel XML document containing the following structure:

xml
<Workbook xmlns='urn:schemas-microsoft-com:office:spreadsheet'
 xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet'>
 <Worksheet ss:Name='Aircraft'>
 <Table>
 <Row>
 <Cell><Data ss:Type='String'>Manufacturer</Data></Cell>
 <Cell><Data ss:Type='String'>Model</Data></Cell>
 <Cell><Data ss:Type='String'>Registration</Data></Cell>
 </Row>
 <Row>
 <Cell><Data ss:Type='String'>AIRBUS</Data></Cell>
 <Cell><Data ss:Type='String'>A320</Data></Cell>
 <Cell><Data ss:Type='String'>ZS-ABC</Data></Cell>
 </Row>
 </Table>
 </Worksheet>
</Workbook>

The important detail is the default namespace declared on the Workbook element.

Every unprefixed element beneath it inherits the namespace unless another namespace is explicitly declared.

A developer might try accessing the rows directly:

php
<?php
$xml = simplexml_load_file('aircraft.xml');

foreach ($xml->Worksheet->Table->Row as $row) {
 echo $row->Cell->Data;
}

Although SimpleXML can sometimes navigate elements in a default namespace through ordinary property access, this approach becomes difficult to maintain when documents contain multiple namespaces and additional spreadsheet structures.

The more explicit solution is to use namespace-aware XPath expressions.

Register the SpreadsheetML namespace

PHP provides SimpleXMLElement::registerXPathNamespace() to associate a namespace URI with a prefix used in XPath queries.

php
<?php
$xml = simplexml_load_file('aircraft.xml');

if ($xml === false) {
 throw new RuntimeException('Unable to load the XML file.');
}

$xml->registerXPathNamespace(
 'ss',
 'urn:schemas-microsoft-com:office:spreadsheet'
);

$rows = $xml->xpath('//ss:Worksheet/ss:Table/ss:Row');

foreach ($rows as $row) {
 echo 'Worksheet row found' . PHP_EOL;
}

The prefix ss in this example is an XPath alias. It does not need to match the prefix used by the XML document.

The namespace URI is what identifies the elements.

The XPath expression searches for Row elements inside Table elements belonging to Worksheet elements. It ignores unrelated XML such as workbook formatting and document properties.

See the PHP XPath namespace documentation for additional examples.

Extract spreadsheet cells into PHP arrays

Once the rows are available, each Row can be processed to extract its Cell elements.

For basic SpreadsheetML documents without omitted columns or merged cells, the following approach works:

php
<?php
$xml = simplexml_load_file('aircraft.xml');

if ($xml === false) {
 throw new RuntimeException('Invalid XML document.');
}

$namespace = 'urn:schemas-microsoft-com:office:spreadsheet';

$xml->registerXPathNamespace('ss', $namespace);

$rows = $xml->xpath('//ss:Worksheet/ss:Table/ss:Row');

$result = [];

foreach ($rows as $row) {
 $values = [];

 foreach ($row->children($namespace)->Cell as $cell) {
 $values[] = trim((string) $cell->children($namespace)->Data);
 }

 $result[] = $values;
}

print_r($result);

The result is a normal PHP array containing the spreadsheet values.

This is useful for importing data into databases, generating reports or passing spreadsheet records to an API.

However, this simple approach has an important limitation: it assumes that every Cell element represents the next column.

Excel XML does not always work that way.

Understanding ss:Index and missing cells

SpreadsheetML can omit empty cells to reduce file size. When this happens, the next populated cell may contain an ss:Index attribute indicating its actual column position.

For example:

xml
<Row>
 <Cell><Data ss:Type='String'>AIRBUS</Data></Cell>
 <Cell ss:Index='3'>
 <Data ss:Type='String'>ZS-ABC</Data>
 </Cell>
</Row>

This row contains two Cell elements but represents three spreadsheet columns.

The first value belongs to column 1, while the second belongs to column 3. Column 2 is empty.

A parser that simply appends values to an array will incorrectly place ZS-ABC in column 2.

To prevent this, read the ss:Index attribute and track column positions explicitly.

The index is one-based, meaning column A is 1, column B is 2 and column C is 3.

Handling merged cells with ss:MergeAcross

SpreadsheetML also supports merged cells.

A cell containing ss:MergeAcross='2' occupies its starting column and the following two columns.

When calculating the position of the next cell, the parser must advance by three columns rather than one.

The attribute describes the additional columns occupied by the merged cell. It does not mean the same value should automatically be copied into every merged column.

This distinction matters when parsing reports with large headings, merged titles and irregular layouts.

Complete PHP example: Extract aircraft information

The original problem involves an Excel XML report containing aircraft registrations, manufacturers and models.

The required values appear in columns 5, 3 and 4 respectively. Column 1 contains a record number that can help distinguish aircraft records from headers and summary rows.

The following example accounts for missing and merged cells while extracting those fields.

Save it as parse-aircraft.php and place the exported XML file beside it as aircraft.xml. PHP must have the SimpleXML extension enabled.

php
<?php
declare(strict_types=1);

$path = __DIR__ . '/aircraft.xml';

if (!is_file($path) || !is_readable($path)) {
 throw new RuntimeException('XML file does not exist or is unreadable.');
}

$xml = simplexml_load_file(
 $path,
 SimpleXMLElement::class,
 LIBXML_NONET
);

if ($xml === false) {
 throw new RuntimeException('Unable to parse the XML document.');
}

$namespace = 'urn:schemas-microsoft-com:office:spreadsheet';

$xml->registerXPathNamespace('ss', $namespace);

$rows = $xml->xpath('//ss:Worksheet/ss:Table/ss:Row');

if ($rows === false) {
 throw new RuntimeException('Unable to locate worksheet rows.');
}

$aircraft = [];

foreach ($rows as $row) {
 $columns = [];
 $columnNumber = 1;

 foreach ($row->children($namespace)->Cell as $cell) {
 $attributes = $cell->attributes($namespace);

 if (isset($attributes['Index'])) {
 $columnNumber = (int) $attributes['Index'];
 }

 $data = $cell->children($namespace)->Data;
 $columns[$columnNumber] = trim((string) $data);

 $mergeAcross = isset($attributes['MergeAcross'])
 ? (int) $attributes['MergeAcross']
 : 0;

 $columnNumber += 1 + $mergeAcross;
 }

 // Skip headings, blank rows and summary records.
 if (!ctype_digit($columns[1] ?? '')) {
 continue;
 }

 $manufacturer = $columns[3] ?? '';
 $model = $columns[4] ?? '';
 $registration = $columns[5] ?? '';

 if ($manufacturer === '' || $registration === '') {
 continue;
 }

 $aircraft[] = [
 'manufacturer' => $manufacturer,
 'model' => $model,
 'registration' => $registration,
 ];
}

$json = json_encode(
 $aircraft,
 JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR
);

echo $json . PHP_EOL;

For the sample aircraft data, a record would have the following structure:

json
{
 "manufacturer": "LEARJET INC.",
 "model": "Learjet Model 45",
 "registration": "I-AVNK"
}

The result can be inserted into MySQL using prepared PDO statements, exported as JSON or processed by another business application.

The example deliberately keeps column mapping separate from XML navigation. If a future report changes its layout, the extraction rules can be adjusted without replacing the entire parser.

For files containing multiple worksheets, add a worksheet-name filter before processing if only one sheet is relevant. Otherwise, the XPath expression will collect rows from every matching worksheet.

Excel XML is not the same as XLSX

This approach applies to Excel 2003 XML SpreadsheetML documents, which are plain XML files.

Modern XLSX workbooks use a ZIP-based Office Open XML format containing multiple XML files and associated resources.

Do not expect simplexml_load_file() to read an XLSX workbook directly.

For modern Excel formats, a library such as PhpSpreadsheet is generally more suitable.

Security and performance considerations

Avoid enabling XML external entity expansion when processing files from untrusted sources. The example uses LIBXML_NONET to prevent network access by the XML parser, but that option alone is not a complete XML security policy. Validate uploaded files, restrict accepted file sizes and keep XML parser configuration conservative.

SimpleXML loads the document into memory. This is convenient for smaller reports but may become expensive when processing very large XML exports.

For large files, consider PHP's XMLReader extension, which supports streaming through XML content without keeping the entire document structure in memory.

Final checks

Before using the parser in production, test documents containing missing cells, merged headings, multiple worksheets, unexpected columns and empty Data elements.

Remember that ss:Index controls the actual column position, while ss:MergeAcross affects where the next cell begins. Ignoring these attributes can silently produce incorrect data mappings.

For further reference, consult the PHP SimpleXML documentation and the original Stack Overflow discussion.

For applications that regularly import spreadsheet data, isolate the parsing logic in a reusable function and validate the extracted records before inserting them into a database.

WhatsApp us