簡體   English   中英

在PHP中使用XPath解析XML

[英]Parse XML with XPath In PHP

我只需要回顯ID和標題,我已經使用Xpath和xml來獲取詳細信息...我需要在單獨的行中回顯每個ID和標題。

<?php
$xml = <<< XML
<data>
    <metadata>
        <total_elements>183</total_elements>
        <elements_per_page>100</elements_per_page>
        <total_pages>2</total_pages>
    </metadata>
    <spl>
        <id>ID1</id>
        <version>2</version>
        <title>Title 1</title>
        <published_date>Oct 06, 2017</published_date>
    </spl>
    <spl>
        <id>ID2</id>
        <version>2</version>
        <title>Title 2</title>
        <published_date>Oct 05, 2017</published_date>
    </spl>
    <spl>
        <id>ID3</id>
        <version>2</version>
        <title>Title 3</title>
        <published_date>Oct 04, 2017</published_date>
    </spl>
</data>
XML;

$errorSetting = libxml_use_internal_errors(TRUE);
$feed = new DOMDocument();
$feed->loadXML($xml);
libxml_clear_errors();
libxml_use_internal_errors($errorSetting);

$xpath = new DOMXPath($feed);

foreach ($xpath->query('//spl') as $spl) {
    foreach ($spl->childNodes as $child) 
    {
        if (($child->nodeValue) !== '') 
        {
            echo \htmlspecialchars($child->nodeValue);

        }
    }
}
?>

這給出了輸出:

ID1
2
Title 1
Oct 06, 2017

ID2
2
Title 2
Oct 05, 2017

ID3
2
Title 3
Oct 04, 2017

或者,我嘗試了:

foreach ($xpath->query('//id') as $id) 
    {
        if (($id->nodeValue) !== '') {
         echo \htmlspecialchars($id->nodeValue);                
        }
    foreach ($xpath->query('//title') as $title) { 
        echo \htmlspecialchars($title->nodeValue); 
        }

    }

但是它給出的輸出為:

ID1 Title 1 Title 2 Title 3
ID2 Title 1 Title 2 Title 3
ID3 Title 1 Title 2 Title 3

我需要輸出為:

ID1 Title 1
ID2 Title 2
ID3 Title 3

如果將foreach循環更改為

foreach ($xpath->query('//spl') as $spl) {
    echo $xpath->evaluate("string(descendant::id/text())", $spl);
    echo $xpath->evaluate("string(descendant::title/text())", $spl);
    echo PHP_EOL;
}

這將遍歷所有spl元素,然后內部XPath提取id和title(后代確保它只是封閉元素中的項目)。 使用evaluate()意味着在這種情況下,返回值不是字符串,而不是獲取節點。 同樣在evaluate()我使用$spl作為查詢的起點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM