0

我编写了以下 php 代码来从此 xml 中提取节点信息:

<sioctBoardPost rdfabout="http//boards.ie/vbulletin/showpost.php?p=67075">
  <rdftype rdfresource="http//rdfs.org/sioc/ns#Post" />
  <dctitle>hib team</dctitle>
  <siochas_creator>
    <siocUser rdfabout="http//boards.ie/vbulletin/member.php?u=497#user">
      <rdfsseeAlso rdfresource="http//boards.ie/vbulletin/sioc.php?sioc_type=user&amp;sioc_id=497" />
    </siocUser>
  </siochas_creator>
  <dctermscreated>1998-04-25T213200Z</dctermscreated>
  <sioccontent>zero, those players that are trialing 300 -400 pingers? umm..mager lagg and even worse/</sioccontent>
</sioctBoardPost>

<?php
$xml = simplexml_load_file("boards.xml");
$products[0] = $xml->xpath("/sioctBoardPost/sioccontent");
$products[1] = $xml->xpath("/sioctBoardPost/dctermscreated");
$products[2] = $xml->xpath("/sioctBoardPost/@rdfabout");
print_r($products);
  ?>

这给出了以下输出:

Array ( 
[0] => Array ( [0] => SimpleXMLElement Object ( [0] => zero, those players that are trialing for hib team, (hpb's) most of them are like 300 -400 pingers? umm..mager lagg and even worse when they play on uk server's i bet/ ) ) [1] => Array ( [0] => SimpleXMLElement Object ( [0] => 1998-04-25T213200Z ) ) [2] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [rdfabout] => http//boards.ie/vbulletin/showpost.php?p=67075 ) ) ) 
) 

但我只需要节点内容作为输出,即没有 Array([0] => Array 等。

输出应该是这样的:

zero, those players that are trialing for hib team, (hpb's) most of them are like 300 -400 pingers? umm..mager lagg and even worse when they play on uk server's i bet

1998-04-25T213200Z

http//boards.ie/vbulletin/showpost.php?p=67075

提前致谢

4

3 回答 3

1

您可以使用current()仅获取每个 XPath 结果的第一个元素(这是一个数组),然后使用(string)强制转换来获取节点内容:

$products[0] = (string)current($xml->xpath("/sioctBoardPost/sioccontent"));
$products[1] = (string)current($xml->xpath("/sioctBoardPost/dctermscreated"));
$products[2] = (string)current($xml->xpath("/sioctBoardPost/@rdfabout"));
print_r($products);
于 2013-01-17T06:01:17.720 回答
0

正如您所观察到的,该xpath()方法返回一个匹配节点的数组,因此您需要处理返回数组的元素。我相信这应该适用于这种情况:

$xml = simplexml_load_file("boards.xml");
$products[0] = $xml->xpath("/sioctBoardPost/sioccontent")[0];
$products[1] = $xml->xpath("/sioctBoardPost/dctermscreated")[0];
$products[2] = $xml->xpath("/sioctBoardPost/@rdfabout")[0];
print_r($products);
于 2013-01-17T05:53:02.580 回答
0

这应该可以满足您的需求...

foreach ($products as $product) { // iterate through the $products array
    print $product[0]->nodeValue  // output the node value of the SimpleXMLElement Object
}
于 2013-01-17T06:06:50.370 回答