1 回答
TA贡献1860条经验 获得超9个赞
PHP DOM 支持 Xpath 表达式来获取特定节点和值。这大大减少了您需要的循环和条件的数量。
这是一个演示:
// 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 关注
- 101 浏览
添加回答
举报