0

我有以下工作示例来检索返回 SimpleXMLElement 对象的特定维基百科页面:

ini_set('user_agent', 'michael@example.com');
$doc = New DOMDocument();
$doc->load('http://en.wikipedia.org/w/api.php?action=parse&page=Main%20Page&format=xml');

$xml = simplexml_import_dom($doc);

print '<pre>';
print_r($xml);
print '</pre>';

返回:

SimpleXMLElement Object
(
    [parse] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [title] => Main Page
                    [revid] => 472210092
                    [displaytitle] => Main Page
                )

            [text] => <body><table id="mp-topbanner" style="width: 100%;"...

愚蠢的问题/头脑空白。我想要做的是捕获 $xml->parse->text 元素并依次解析它。所以最终我想要返回的是以下对象;我该如何做到这一点?

SimpleXMLElement Object
(
    [body] => SimpleXMLElement Object
        (
            [table] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [id] => mp-topbanner
                            [style] => width:100% ...
4

1 回答 1

1

在喝了一杯新鲜的茶和吃一根香蕉后,这是我想出的解决方案:

ini_set('user_agent','michael@example.com');
$doc = new DOMDocument();
$doc->load('http://en.wikipedia.org/w/api.php?action=parse&page=Main%20Page&format=xml');
$nodes = $doc->getElementsByTagName('text');

$str = $nodes->item(0)->nodeValue;

$html = new DOMDocument();
$html->loadHTML($str);

然后,这允许我获得一个元素值,这就是我所追求的。例如:

echo "Some value: ";
echo $html->getElementById('someid')->nodeValue;
于 2012-01-21T02:52:10.463 回答