如何获取SimpleXmlElement属性的值?

时间:2019-08-24 10:02:15

标签: php simplexml

我有以下XML代码:

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

在PHP中,我有以下代码:

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

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

foreach没有运行。

我也尝试过:

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

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

我当然可以将XML转换为字符串并执行一些正则表达式魔术,但是我认为这不是一个好方法。

更新:

这是整个XML文档代码:

<?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>

如何访问w:typer:id属性值?

1 个答案:

答案 0 :(得分:1)

您必须将属性名称空间作为attributes的参数传递

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

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

与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);
}