I have an XML file structured like this
<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>
I need to make an associative array that consists of the "sid" attributes and main series titles like this
array(
123 => "Series 123 Main Title",
456 => "Series 456 Main Title",
//...
);
I tried using this xpath query //series/title[@type="main"]
and I get the nodelist
$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;
}
Results in
$series = array(
0 => "Series 123 Main Title",
1 => "Series 456 Main Title",
//...
);
But I need parent's "sid" attribute too. How could I do that in a non-resource-intensive way?
Quite simple. Just reference the parent node to $title
:
foreach($titles as $title) {
$id = $title->parentNode->getAttribute('sid');
$series[$id] = $title->nodeValue;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.