1 回答

TA貢獻1860條經(jīng)驗 獲得超9個贊
PHP DOM 支持 Xpath 表達式來獲取特定節(jié)點和值。這大大減少了您需要的循環(huán)和條件的數(shù)量。
這是一個演示:
// bootstrap the XML document
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$data = [];
// iterate the node element nodes
foreach ($xpath->evaluate('/books/book') as $book) {
$authors = array_map(
fn ($node) => $node->textContent,
// fetch author name nodes as an array
iterator_to_array($xpath->evaluate('authors/author/name', $book))
);
$data[] = [
// cast first name element child to string
$xpath->evaluate('string(name)', $book),
// cast first year element child to string
$xpath->evaluate('string(year)', $book),
implode(', ', $authors)
];
}
var_dump($data);
- 1 回答
- 0 關(guān)注
- 137 瀏覽
添加回答
舉報