我有以下工作示例来检索返回SimpleXMLElement对象的特定Wikipedia页面:
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-&gt; parse-&gt;文本元素,然后解析它。所以最终我要返回的是以下对象;我该如何实现这个目标?
SimpleXMLElement Object
(
[body] => SimpleXMLElement Object
(
[table] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => mp-topbanner
[style] => width:100% ...
答案 0 :(得分: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;