0

我尝试了多种代码组合,即使我认为我掌握了它,它也失败了!我总是回到“获取非对象错误的属性”我目前的一个是:

Notice: Trying to get property of non-object in {PROJECT_DIR} on line 11

无论如何,我正在尝试更改 .docx 文件 document.xml 文件中书签的节点值,并且我有一组书签 id => 书签名称,我正在使用简单的 foreach 遍历它们来编辑所有使用 SimpleXML 找到了书签,但是,我遇到了一些问题。

我目前的代码是:

if (file_exists('document.xml'))
{
    $document = simplexml_load_file('document.xml');
}
echo $document->getName() . "<br />";
echo $document->document->body->{'w:bookmarkStart'};

我尝试从 echo 语句中删除 ->document 并将 {'w:bookmarkStart'} 更改为 bookmarkStart 但一切都证明无效,但是我说我尝试的上述更改没有返回通知,只是空白。我确定我还没有掌握这个 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: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 wp14">
    <w:body>
            <w:bookmarkStart w:id="0" w:name="MOREG"/>
            <w:bookmarkEnd w:id="0"/>
    </w:body>
</w:document>
4

2 回答 2

0

也许这会有所帮助? $document->xpath("//w:bookmarkEnd"); 使用 xpath 查询可能更实用,并且可以很好地选择节点。(也许这里有人可以帮助您找到一种方法来按照您的方式进行操作,如果没有帮助,请见谅)

于 2012-08-18T19:07:28.747 回答
0

不幸的是,名称空间(示例中的<w:...表示法和xmlns:w="..."声明)使 SimpleXML 变得不那么简单。

首先要知道的是,w:前缀实际上只是“真实”命名空间的本地别名,也就是对应xmlns:w属性定义的 URI——在这种情况下,'http://schemas.openxmlformats.org/wordprocessingml/2006/main'

要知道的第二件事是,要获取默认(无前缀)命名空间以外的任何元素,您需要使用 SimpleXML 方法->children($namespace)->attributes($namespace)

因此,经过一些反复试验,我让您的示例 XML 使用以下命令输出“MOREG”:

$w = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
echo $document->children($w)->body->bookmarkStart['name'];

如果您使用的是 PHP ≥ 5.2,您实际上可以通过传递truechildren方法来使用“w”前缀,将事情简化为:

echo $document->children('w', TRUE)->body->bookmarkStart['name'];
于 2012-08-18T19:08:49.540 回答