鉴于PHP代码:
$xml = <<<EOF
<articles>
<article>
This is a link
<link>Title</link>
with some text following it.
</article>
</articles>
EOF;
function traverse($xml) {
$result = "";
foreach($xml->children() as $x) {
if ($x->count()) {
$result .= traverse($x);
}
else {
$result .= $x;
}
}
return $result;
}
$parser = new SimpleXMLElement($xml);
traverse($parser);
Run Code Online (Sandbox Code Playgroud)
我期望函数traverse()返回:
This is a link Title with some text following it.
Run Code Online (Sandbox Code Playgroud)
但是,它仅返回:
Title
Run Code Online (Sandbox Code Playgroud)
有没有办法使用simpleXML获得预期的结果(显然是为了消耗数据而不是像在这个简单的例子中那样返回它)?
谢谢,N.
Jos*_*vis 17
可能有方法只使用SimpleXML实现您想要的功能,但在这种情况下,最简单的方法是使用DOM.好消息是,如果您已经在使用SimpleXML,则不必更改任何内容,因为DOM和SimpleXML 基本上可以互换:
// either
$articles = simplexml_load_string($xml);
echo dom_import_simplexml($articles)->textContent;
// or
$dom = new DOMDocument;
$dom->loadXML($xml);
echo $dom->documentElement->textContent;
Run Code Online (Sandbox Code Playgroud)
假设您的任务是迭代每个<article/>并获取其内容,您的代码将如下所示
$articles = simplexml_load_string($xml);
foreach ($articles->article as $article)
{
$articleText = dom_import_simplexml($article)->textContent;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15860 次 |
| 最近记录: |