【问题标题】:How to return only the first tag in my XML Parser?如何只返回我的 XML Parser 中的第一个标签?
【发布时间】:2013-06-13 12:49:56
【问题描述】:

如何只返回我的 XML 中的第一个标签? XML 是这样的:

<destinationname>New York City</destinationname>
<destinationname>New York</destinationname>
<destinationname>New Jersey</destinationname>

这是一个假期。每个假期都有不同数量的目的地名称。一些只有一个,一些 2-4 个名字......我总是想只返回第一个标签。

这是我的 XML 解析器的一部分:

// assign the $data by the $this->element
        switch ($this->element) {
            case "destinationname":
                $this->item['zielgebiet'] .= $data;
                break;
            }

在它返回的那一刻:“New York CityNew YorkNew Jersey”

非常感谢您的帮助 ;-)

【问题讨论】:

    标签: php xml parsing tags return


    【解决方案1】:
    $xml = '
    <root>
    <destinationname>New York City</destinationname>
    <destinationname>New York</destinationname>
    <destinationname>New Jersey</destinationname>
    </root>
    ';
    
    $d = new SimpleXMLElement($xml);
    
    $nodes = $d->destinationname;
    
    print $nodes[0] . PHP_EOL;
    

    【讨论】:

      【解决方案2】:

      在外循环中使用break; 语句。或者如果你在一个函数中使用return $data;

      【讨论】:

        【解决方案3】:

        很简单:

        $xml = simplexml_load_string($x); // assume XML in $x
        echo $xml->destinationname[0];
        

        看到它的工作:http://3v4l.org/JUOU1

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-24
          • 1970-01-01
          • 2021-11-18
          • 1970-01-01
          相关资源
          最近更新 更多