首页 文章

php - 如何通过 id 获取 xml 标记

提问于
浏览
-3

我有这种格式的 XML

<hotels>
    <hotel>
        <id>285</id>
        <name>Alexander</name>
        <price>250 USD</price>
    </hotel>

    <hotel>
        <id>678</id>
        <name>Hilton</name>
        <price>480 USD</price>
    </hotel>                
</hotels>

如何使用 PHP 获取 id 为 678 的酒店名称?

3 回答

  • 1

    使用simplexml_load_string()解析 xml 字符串。然后遍历hotel标签并检查id的内容

    $xml = simplexml_load_string($str);
    foreach($xml->hotel as $hotel)
        $hotel->id == "678" ? @$name = (string)$hotel->name : '';
    echo $name;
    

    检查结果演示


    如果你不想使用foreach,也可以使用DOMXpath

    $doc = new DOMDocument();
    $doc->loadXML($str);
    $name = (new DOMXpath($doc))->query("//hotel[id[text()='678']]/name")[0]->nodeValue;
    // Hilton
    

    检查结果演示

  • 0

    我希望这是你正在寻找的:

    $xmlstr = <<<XML
    <hotels>
        <hotel>
            <id>285</id>
            <name>Alexander</name>
            <price>250 USD</price>
        </hotel>
    
        <hotel>
            <id>678</id>
            <name>Hilton</name>
            <price>480 USD</price>
        </hotel>                
    </hotels>
    XML;
    
    $hotel = new SimpleXMLElement($xmlstr);
    $list = $hotel->hotel;
    $count = count($list);
    while($count > 0){
        $count--;
        $id = $hotel->hotel[$count]->id;
        if($id == 678){
            $name = $hotel->hotel[$count]->name;
            echo $name;
        }
    }
    
  • 0

    您可以使用 SimpleXML 和 XPath 查找酒店而无需使用循环。

    $data ='<hotels>
        <hotel>
            <id>285</id>
            <name>Alexander</name>
            <price>250 USD</price>
        </hotel>
    
        <hotel>
            <id>678</id>
            <name>Hilton</name>
            <price>480 USD</price>
        </hotel>
    </hotels>';
    
    $hotel = new SimpleXMLElement($data);
    $hotel678 = $hotel->xpath("//hotel[id='678']");
    echo $hotel678[0]->name;
    

相关问题