PHP获取父级ID => child的值作为XML中的数组

时间:2010-09-28 13:00:37

标签: php xml xpath domdocument

我有一个像这样结构的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”属性。我怎么能以非资源密集的方式做到这一点?

1 个答案:

答案 0 :(得分:1)

非常简单。只需将parent node引用至$title

即可
foreach($titles as $title) {
    $id = $title->parentNode->getAttribute('sid');
    $series[$id] = $title->nodeValue;
}