PHP XML 使用 simplexml_load_string 从复杂的 XML 中获取数据


php xml get data from complicated xml using simplexml_load_string

<1:1>
    <1:b/>
    <1:body>
        <1:P>
            <1:PPR></1:PPR>
            <1:r>
                <1:rPR></1:rPR>
                <1:t>text here</1:t>
            </1:r>
        </1:P>
    </1:body>
</1:1>

我的XML看起来像这样,我需要从每个"1:P"中获取"1:T"

但是我遇到了一些问题,因为我不能只是$document->1:1->1:body->1:P->1:r->1:t因为它不喜欢冒号

谁能想到解决这个问题的方法?我试过把它们放在变量中,但没有快乐......

这是我到目前为止所拥有的:

$document = simplexml_load_string($xml);
$body = "1:body";
$r = "1:r";
$t = "1:t";
foreach ($document->$body as $p) {
    echo $p->$r->$t;
}

XML 元素名称不能以数字开头。您的代码将产生大量警告,不幸的是,XML 将无法解析。

Warning: simplexml_load_string(): Entity: line 1: parser error : StartTag: invalid element name in /Users/joelhinz/Kod/test/test.php on line 16
Warning: simplexml_load_string(): <1:1> in /Users/joelhinz/Kod/test/test.php on line 16
Warning: simplexml_load_string():  ^ in /Users/joelhinz/Kod/test/test.php on line 16
Warning: simplexml_load_string(): Entity: line 1: parser error : Extra content at the end of the document in /Users/joelhinz/Kod/test/test.php on line 16
Warning: simplexml_load_string(): <1:1> in /Users/joelhinz/Kod/test/test.php on line 16
Warning: simplexml_load_string():  ^ in /Users/joelhinz/Kod/test/test.php on line 16
Warning: Invalid argument supplied for foreach() in /Users/joelhinz/Kod/test/test.php on line 20

我想,您必须将其转换为适当的XML,或者使用不那么挑剔的解析器。

关于结肠问题,如果你让其余的工作,你可能会做$document->{1:1}->{1:body}等等。