繁体   English   中英

如何在PHP中解析此XML提要?

[英]How do parse this XML feed in PHP?

我需要在PHP中解析以下荒谬的XML提要。 它来自一家房地产公司,他们不认为具有“属性类型”节点-而是具有用于公寓的“公寓”节点,用于房屋的“房屋”节点等。我的问题是我需要提取子项这些节点以获取“卧室”,“ sub_type”和其他信息(这是原始版本的精简版本)。

<properties>
<property>
    <general_info>
        <id>1</id>
    </general_info>
    <apartment>
        <sub_type>1</sub_type>
        <bedrooms>2</bedrooms>
    </apartment>
</property>
<property>
    <general_info>
        <id>2</id>
    </general_info>
    <house>
        <sub_type>3</sub_type>
        <bedrooms>5</bedrooms>
    </house>
</property>
<property>
    <general_info>
        <id>3</id>
    </general_info>
    <business>
        <sub_type>6</sub_type>
        <bedrooms>0</bedrooms>
    </business>
</property>

我正在使用simplexml_load_file来“获取”提要,并在元素上执行foreach循环。 经过一番研究,看来xpath会有所帮助,但我无法使其正常工作。

这是我的代码的基础:

$xmlObject = simplexml_load_file($XML_FILE_NAME);

foreach($xmlObject->property as $property)
{

    // Get Property sub-type
    $property_sub_types = $property->xpath('//sub_type');
    foreach($property_sub_types as $sub_type)
    {
        print_r($sub_type); // printing to screen for demo purposes
    }
}

这是我得到的输出。 正确的值,但显示3次而不是1次。

SimpleXMLElement Object
(
    [0] => 1
)
SimpleXMLElement Object
(
    [0] => 3
)
SimpleXMLElement Object
(
    [0] => 6
)
SimpleXMLElement Object
(
    [0] => 1
)
SimpleXMLElement Object
(
    [0] => 3
)
SimpleXMLElement Object
(
    [0] => 6
)
SimpleXMLElement Object
(
    [0] => 1
)
SimpleXMLElement Object
(
    [0] => 3
)
SimpleXMLElement Object
(
    [0] => 6
)

如果有人能指出我正确的方向,将不胜感激。 哦,在你问之前,让他们重做他们的提要不是一种选择。

Please find below code :
Are you exactly want to like this?


$xmlObject = simplexml_load_file("XML File Path");
//print_r($xmlObject);
foreach($xmlObject->property as $property)
{    
    foreach($property as $test){
        //print_r($test->sub_type);
        echo "Bedrooms:-" .$test->bedrooms."&nbsp;&nbsp;&nbsp;"; 
        echo "Sub Type:".$test->sub_type;
      //print_r($property->business->sub_type);
      echo "</br>";
    }   
}

您的xpath //sub_type选择整个文档中的所有sub_type元素。
将其更改为.//sub_type应该会有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM