netdjw
netdjw

Reputation: 5997

How to get SimpleXmlElement attribute's value?

I have this XML code:

<w:footerReference w:type="default" r:id="rId6"/>

In PHP I have this code:

// $footer is a SimpleXMLElement, contain the code above

foreach ($footer->attributes() as $attr_name => $attr_value) {
    dd($attr_name." = ".$attr_value);
}

And the foreach isn't run.

I tried this too:

$type = 'type';
$footer->attributes()->$type; // empty string

$wtype = 'w:type';
$footer->attributes()->$wtype; // empty string

Of course I can convert XML to string and do some regex magic, but it isn't a good way in my opinion.

UPDATE:

Here is the entire XML document code:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:o="urn:schemas-microsoft-com:office:office" 
    xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" 
    xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" 
    xmlns:v="urn:schemas-microsoft-com:vml" 
    xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" 
    xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" 
    xmlns:w10="urn:schemas-microsoft-com:office:word" 
    xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" 
    xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" 
    xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" 
    xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" 
    xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" 
    xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" 
    xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 w15 wp14">
    <w:body>
        <w:sectPr w:rsidR="00654EDA">
            <w:footerReference w:type="default" r:id="rId6"/>
        </w:sectPr>
    </w:body>
</w:document>

How can I access the w:type and r:id attributes values?

Upvotes: 1

Views: 83

Answers (1)

Błażej Kowalczyk
Błażej Kowalczyk

Reputation: 184

You have to pass attribute namespace as paramter of attributes

$type = $footer->attributes("http://schemas.openxmlformats.org/wordprocessingml/2006/main")->type;

$id = $footer->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships")->id;

the same with foreach

foreach ($footer->attributes("http://schemas.openxmlformats.org/wordprocessingml/2006/main") as $attr_name => $attr_value) {
    dd($attr_name." = ".$attr_value);
}
foreach ($footer->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships") as $attr_name => $attr_value) {
    dd($attr_name." = ".$attr_value);
}

Upvotes: 1

Related Questions