【发布时间】:2014-11-02 03:34:18
【问题描述】:
这是我尝试解析的 xml 文件(odt-file)的结构:
<office:body>
<office:text>
<text:h text:style-name="P1" text:outline-level="2">Chapter 1</text:h>
<text:p text:style-name="Standard">Lorem ipsum. </text:p>
<text:h text:style-name="Heading3" text:outline-level="3">Subtitle 2</text:h>
<text:p text:style-name="Standard"><text:span text:style-name="T5">10</text:span><text:span text:style-name="T6">:</text:span><text:s/>Text (100%)</text:p>
<text:p text:style-name="Explanation">Further informations.</text:p>
<text:p text:style-name="Standard">9.7:<text:s/>Text (97%)</text:p>
<text:p text:style-name="Explanation">Further informations.</text:p>
<text:p text:style-name="Standard"><text:span text:style-name="T9">9.1:</text:span><text:s/>Text (91%)</text:p>
<text:p text:style-name="Explanation">Further informations.</text:p>
<text:p text:style-name="Explanation">More furter informations.</text:p>
</office:text>
</office:body>
使用 XML-Reader 我是这样做的:
while ($reader->read()){
if ($reader->nodeType == XMLREADER::ELEMENT && $reader->name === 'text:h') {
if ($reader->getAttribute('text:outline-level')=="2") $html .= '<h2>'.$reader->expand()->textContent.'</h2>';
}
elseif ($reader->nodeType == XMLREADER::ELEMENT && $reader->name === 'text:p') {
if ($reader->getAttribute('text:style-name')=="Standard") {
$html .= '<p>'.$reader->readInnerXML().'<p>';
}
else if {
// Doing something different
}
}
}
echo $html;
现在我想对 DOMDocument 做同样的事情,但我需要一些语法方面的帮助。如何遍历所有办公室的孩子:文本?在遍历所有节点时,我会通过 if/else 检查要做什么(文本:h 与文本:p)。
我还需要用空格替换每个 text:s(如果 text:p 中有这样的元素)...
$reader = new DOMDocument();
$reader->preserveWhiteSpace = false;
$reader->load('zip://content.odt#content.xml');
$body = $reader->getElementsByTagName( 'office:text' )->item( 0 );
foreach( $body->childNodes as $node ) echo $node->nodeName . PHP_EOL;
或者循环遍历所有文本元素会更聪明吗?如果是这种情况,仍然是问题,如何做到这一点。
$elements = $reader->getElementsByTagName('text');
foreach($elements as $node){
foreach($node->childNodes as $child) {
echo $child->nodeName.': ';
echo $child->nodeValue.'<br>';
// check for type...
}
}
【问题讨论】:
标签: php xml domdocument