PHP中的DOM元素GetElementByTagName问题

时间:2016-09-16 15:11:35

标签: php dom getelementsbytagname

<FlightSegment DepartureDateTime="2016-09-20T06:05:00" ArrivalDateTime="2016-09-20T08:05:00" FlightNumber="716" ResBookDesigCode="N">
    <FlightDuration>2016-09-14T02:00:00</FlightDuration>
    <DepartureAirport LocationCode="IST" Terminal="I" />
    <ArrivalAirport LocationCode="KBP" />
    <OperatingAirline Code="PS" />
    <Equipment AirEquipType="73H" />
    <MarketingAirline Code="PS" />
    <BookingClassAvails>
        <BookingClassAvail ResBookDesigCode="N" ResBookDesigQuantity="9" RPH="ADT" AvailablePTC="ADT" ResBookDesigCabinCode="M" FareBasis="NL1LTP4" />
    </BookingClassAvails>
</FlightSegment>
<FlightSegment DepartureDateTime="2016-09-20T09:50:00" ArrivalDateTime="2016-09-20T11:55:00" FlightNumber="101" ResBookDesigCode="N">
    <FlightDuration>2016-09-14T03:05:00</FlightDuration>
    <DepartureAirport LocationCode="KBP" />
    <ArrivalAirport LocationCode="AMS" />
    <OperatingAirline Code="PS" />
    <Equipment AirEquipType="73R" />
    <MarketingAirline Code="PS" />
    <BookingClassAvails>
        <BookingClassAvail ResBookDesigCode="N" ResBookDesigQuantity="9" RPH="ADT" AvailablePTC="ADT" ResBookDesigCabinCode="M" FareBasis="NL1LTP4" />
    </BookingClassAvails>
</FlightSegment>

有两个航段。 我们在此代码中没有任何标识符,所以,

  1. 如何按块分割此代码以使用第一个<FlightSegment>块中的属性?
  2. 此外,我需要计算<FlightSegments>
  3. 请帮助! )

2 个答案:

答案 0 :(得分:1)

您可以使用此函数将XML节点转换为(嵌套)数组:

function domToArray($node) {
    $arr = [];
    // Add all attributes of this node as key/values:
    foreach ($node->attributes as $attribute) {
        $arr[$attribute->nodeName] = $attribute->nodeValue;
    }
    // Iterate through the child nodes
    foreach ($node->childNodes as $child) {
        if ($child->nodeType === XML_TEXT_NODE) {
            // Assign the text content to a "value" key
            if (trim($child->textContent)!== '') {
                $arr['value'] = $child->textContent;
            }
        } else if ($child->nodeType === XML_ELEMENT_NODE) {
            // Create key/value pairs for child nodes, using recursion.
            // If the children are repeated elements, then build
            // an indexed array, otherwise an associative array.
            if (preg_replace("/y$/", "ie", $child->nodeName) ."s" === $node->nodeName) {
                $arr[] = domToArray($child);
            } else {
                $arr[$child->nodeName] = domToArray($child);
            }
        }
    }
    return $arr;
}

首先必须创建一个DOMDocument并将XML字符串读入其中。请注意,您提供的XML片段需要包含在一个单独的元素中,我故意称之为FlightSegments - FlightSegment的倍数,其中有2个:

$doc = new DOMDocument();
$doc->loadXML("<FlightSegments>$xml</FlightSegments>");

完成后,您可以调用我上面提到的功能:

// Convert XML to nested array:
$flightSegments = domToArray($doc->documentElement);

以下是您可以从该阵列获得的一些输出:

// Number of FlightSegments:
echo "Number of FlightSegment elements: " . count($flightSegments) . "<br>";

echo "DepartureDateTime of first FlightSegment: " . $flightSegments[0]['DepartureDateTime'] . "<br>";

echo "All information:<br>";

print_r ($flightSegments);

eval.in上看到它。

使用您提供的示例XML,上述代码的输出将为:

Number of FlightSegment elements: 2
DepartureDateTime of first FlightSegment: 2016-09-20T06:05:00
All information:
Array
(
    [0] => Array
        (
            [DepartureDateTime] => 2016-09-20T06:05:00
            [ArrivalDateTime] => 2016-09-20T08:05:00
            [FlightNumber] => 716
            [ResBookDesigCode] => N
            [FlightDuration] => Array
                (
                    [value] => 2016-09-14T02:00:00
                )

            [DepartureAirport] => Array
                (
                    [LocationCode] => IST
                    [Terminal] => I
                )

            [ArrivalAirport] => Array
                (
                    [LocationCode] => KBP
                )

            [OperatingAirline] => Array
                (
                    [Code] => PS
                )

            [Equipment] => Array
                (
                    [AirEquipType] => 73H
                )

            [MarketingAirline] => Array
                (
                    [Code] => PS
                )

            [BookingClassAvails] => Array
                (
                    [0] => Array
                        (
                            [ResBookDesigCode] => N
                            [ResBookDesigQuantity] => 9
                            [RPH] => ADT
                            [AvailablePTC] => ADT
                            [ResBookDesigCabinCode] => M
                            [FareBasis] => NL1LTP4
                        )

                )

        )

    [1] => Array
        (
            [DepartureDateTime] => 2016-09-20T09:50:00
            [ArrivalDateTime] => 2016-09-20T11:55:00
            [FlightNumber] => 101
            [ResBookDesigCode] => N
            [FlightDuration] => Array
                (
                    [value] => 2016-09-14T03:05:00
                )

            [DepartureAirport] => Array
                (
                    [LocationCode] => KBP
                )

            [ArrivalAirport] => Array
                (
                    [LocationCode] => AMS
                )

            [OperatingAirline] => Array
                (
                    [Code] => PS
                )

            [Equipment] => Array
                (
                    [AirEquipType] => 73R
                )

            [MarketingAirline] => Array
                (
                    [Code] => PS
                )

            [BookingClassAvails] => Array
                (
                    [0] => Array
                        (
                            [ResBookDesigCode] => N
                            [ResBookDesigQuantity] => 9
                            [RPH] => ADT
                            [AvailablePTC] => ADT
                            [ResBookDesigCabinCode] => M
                            [FareBasis] => NL1LTP4
                        )

                )

        )

)

提供完整XML后的编辑

我不确定您的问题是什么,因为在评论中您共享了成功遍历XML的代码。

请注意,您可以使用上面的函数将完整的XML转换为数组(我对函数进行了一次修正,以正确识别以“y”结尾的标记名称的复数形式。)

以下是在XML上调用它的方法:

$soap = domToArray($xmlDoc->documentElement);

$soap的内容将是(我将其截断):

Array
(
    [soap:Body] => Array
        (
            [SearchFlightResponse] => Array
                (
                    [OTA_AirLowFareSearchRS] => Array
                        (
                            [Version] => 0
                            [HasMoreResult] => Array
                                (
                                    [value] => false
                                )

                            [Success] => Array
                                (
                                )

                            [PricedItineraries] => Array
                                (
                                    [0] => Array
                                        (
                                            [Currency] => USD
                                            [ProviderType] => AmadeusProvider
                                            [SequenceNumber] => 0
                                            [AirItinerary] => Array
                                                (
                                                    [OriginDestinationOptions] => Array
                                                        (
                                                            [0] => Array
                                                                (
                                                                    [RefNumber] => 0
                                                                    [DirectionId] => 0
                                                                    [ElapsedTime] => 0650
                                                                    [FlightSegment] => Array
                                                                        (
                                                                            [DepartureDateTime] => 2016-09-20T09:50:00
                                                                            [ArrivalDateTime] => 2016-09-20T11:55:00
                                                                            [FlightNumber] => 101
                                                                            [ResBookDesigCode] => N
                                                                            [FlightDuration] => Array
                                                                                (
                                                                                    [value] => 2016-09-14T03:05:00
                                                                                )

                                                                            [DepartureAirport] => Array
                                                                                (
                                                                                    [LocationCode] => KBP
                                                                                )

                                                                            [ArrivalAirport] => Array
                                                                                (
                                                                                    [LocationCode] => AMS
                                                                                )

                                                                            [OperatingAirline] => Array
                                                                                (
                                                                                    [Code] => PS
                                                                                )

                                                                            [Equipment] => Array
                                                                                (
                                                                                    [AirEquipType] => 73R
                                                                                )

                                                                            [MarketingAirline] => Array
                                                                                (
                                                                                    [Code] => PS
                                                                                )

                                                                            [BookingClassAvails] => Array
                                                                                (
                                                                                    [0] => Array
                                                                                        (
                                                                                            [ResBookDesigCode] => N
                                                                                            [ResBookDesigQuantity] => 9
                                                                                            [RPH] => ADT
                                                                                            [AvailablePTC] => ADT
                                                                                            [ResBookDesigCabinCode] => M
                                                                                            [FareBasis] => NL1LTP4
                                                                                        )

                                                                                )

现在您可以编写如下代码:

$itineries = $soap['soap:Body']['SearchFlightResponse']['OTA_AirLowFareSearchRS']['PricedItineraries']; 
foreach ($itineries as $itinery) {
    // ... etc. Always array access.
}

答案 1 :(得分:0)

现在你的函数从xml文档的最后一段创建了大量文件:

<?php

function domToArray($node) {
    $arr = [];
    // Add all attributes of this node as key/values:
    foreach ($node->attributes as $attribute) {
        $arr[$attribute->nodeName] = $attribute->nodeValue;
    }
    $useName = true;
    // Iterate through the child nodes
    foreach ($node->childNodes as $child) {
        if ($child->nodeType === XML_TEXT_NODE) {
            // Assign the text content to a "value" key
            if (trim($child->textContent)!== '') {
                $arr['value'] = $child->textContent;
            }
        } else if ($child->nodeType === XML_ELEMENT_NODE) {
            // Create key/value pairs for child nodes, using recursion.
            // If the children are repeated elements, then build
            // an indexed array, otherwise an associative array.
            if ($child->nodeName ."s" === $node->nodeName) {
                $arr[] = domToArray($child);
            } else {
                $arr[$child->nodeName] = domToArray($child);
            }
        }
    }
    return $arr;
}





$xmlDoc = new DOMDocument();
$xmlDoc->load("response.xml");
$soap = domToArray($xmlDoc->documentElement);
print_r($soap);

?>

在这里,您可以完全看到所有文档:response.xml

这里包含$soapArray

你的决定是理想的:

// If the children are repeated elements, then build
// an indexed array, otherwise an associative array.

...但是当我尝试加载response.xml时,它并没有构建索引数组。它只是用最后一个FlightSegment构建了大量......

P.S。我不是同一个人,我们只是一起工作。 )