如何从XML文件中获取特定子项并使用PHP在div上显示其子项

时间:2017-02-10 15:15:07

标签: php html xml simplexml

所以,我有一个看起来像这样的XML文件(名字是虚构的):

<myxmlfile>
  <infos>
     <item>
        <itemChild1>foo1</itemChild1>
        <itemChild2>foo2</itemChild2>
     </item>
     <item>
        <itemChild1>foo1</itemChild1>
        <itemChild2>foo2</itemChild2>
     </item>
     <item>
        <itemChild1>foo1</itemChild1>
        <itemChild2>foo2</itemChild2>
     </item>
     <item>...</item>
     <item>...</item>
     <item>...</item>
     <item>...</item>
     <item>...</item>
     <item>...</item>
  <infos>
</myxmlfile>

我的目标是仅举例说明第三个<item>,并在我的浏览器上显示其子项。我怎样才能做到这一点?

到目前为止,我有这个:

PHP

<?php
$divId = 0;
$url ='myxml.xml';
$xml = simplexml_load_file($url) or die ("Can't connect to URL");
?>

2 个答案:

答案 0 :(得分:2)

访问XML的节点值的最简单方法是使用对象运算符和节点名称,例如$xml->myxmlfile

$xml_data = '
    <myxmlfile>
      <infos>
         <item>foo1</item>
         <item>foo2</item>
         <item>foo3</item>
         <item>foo4</item>
         <item>foo5</item>
      </infos>
    </myxmlfile>
';

$xml = new SimpleXMLElement($xml_data);

foreach($xml->infos->item as $k=>$v) {

    echo $v . '<br>';

}

输出

foo1
foo2
foo3
foo4
foo5

请参阅:http://php.net/manual/en/book.simplexml.php

答案 1 :(得分:0)

我建议您使用DOM extension XPath次查询。你的问题没有准确说明你想要实现的目标,所以这里有几个例子:

$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
// query 3rd item and get the first match
$item = $xpath->query("/myxmlfile/infos/item[3]")->item(0);
// dump item as an XML
echo $doc->saveXML($item) . "\n";
// iterate all children of the item and work with nodes directly
foreach ($xpath->query("./*", $item) as $node) {
    printf("%s has a value of %s\n", $node->nodeName, $node->nodeValue);
}
// iterate all children and dump nodes as an HTML
foreach ($xpath->query("./*", $item) as $node) {
    echo $doc->saveHTML($node) . "\n";
}

这将打印以下内容:

<item>
    <itemChild1>foo1</itemChild1>
    <itemChild2>foo2</itemChild2>
</item>
itemChild1 has a value of foo1
itemChild2 has a value of foo2
<itemChild1>foo1</itemChild1>
<itemChild2>foo2</itemChild2>