我有一个像这样结构的XML文件
<serieslist>
<series sid="123">
<title type="main">Series 123 Main Title</title>
<title type="official">Series 123 Official Title</title>
<title type="short">S 123</title>
</series>
<series sid="456">
<title type="main">Series 456 Main Title</title>
<title type="official">Series 456 Official Title</title>
<title type="short">S 456</title>
</series>
/* +6000 more <series> nodes */
</serieslist>
我需要创建一个由“sid”属性和主要系列标题组成的关联数组,如下所示
array(
123 => "Series 123 Main Title",
456 => "Series 456 Main Title",
//...
);
我尝试使用此xpath查询//series/title[@type="main"]
,然后获取节点列表
$xml = DOMDocument::load('serieslist.xml');
$xpath = new DOMXPath($xml);
$titles = $xpath->query('//series/title[@type="main"]');
$series = array();
foreach($titles as $title) {
$series[] = $title->nodeValue;
}
结果
$series = array(
0 => "Series 123 Main Title",
1 => "Series 456 Main Title",
//...
);
但我也需要父母的“sid”属性。我怎么能以非资源密集的方式做到这一点?
答案 0 :(得分:1)
非常简单。只需将parent node引用至$title
:
foreach($titles as $title) {
$id = $title->parentNode->getAttribute('sid');
$series[$id] = $title->nodeValue;
}