我希望得到xml节点中存在的值,因为我编写了以下代码。
代码目标是获取
1.Board value,
2.Address->City value,
3.Photo->PropertyPhoto->SequenceId value.
代码是:
//some code
$fsp = $xml->saveXML();
echo $fsp; //it's output is given below
$s = simplexml_import_dom($fsp);
echo $s->PropertyDetails[0]->Board;
echo $s->PropertyDetails[0]->Address->City;
echo $s->PropertyDetails[0]->Photo->PropertyPhoto->SequenceId;
echo $ fsp的输出是:
<?xml version="1.0" encoding="UTF-8"?>
<PropertyDetails ID="13953882" LastUpdated="Thu, 09 Jan 2014 01:43:48 GMT">
<ListingID>188691</ListingID>
<Board>117</Board>
<Address>
<StreetAddress>B LOCAL RD</StreetAddress>
<AddressLine1>B LOCAL RD</AddressLine1>
<City>PORT REXTON</City>
<Province>Newfoundland & Labrador</Province>
<PostalCode>A0C2H0</PostalCode>
<Country>Canada</Country>
</Address>
<Photo>
<PropertyPhoto>
<SequenceId>1</SequenceId>
</PropertyPhoto>
<PropertyPhoto>
<SequenceId>12</SequenceId>
</PropertyPhoto>
</Photo>
<ViewType>Ocean view</ViewType>
它没有给出任何输出。
所需的输出是:
117
PORT REXTON
1,12
帮助我。
答案 0 :(得分:1)
首先从var:
中的字符串加载xml$doc = new DOMDocument();
$doc->load($fsp);
apidoc:http://www.php.net/manual/en/domdocument.loadxml.php
然后阅读所请求的标签:
//board
$boards = $doc->getElementsByTagName('Board');
echo $boards[0]->nodeValue, PHP_EOL;
//city
$cities = $doc->getElementsByTagName('City');
echo $cities[0]->nodeValue, PHP_EOL;
//sequence ids
$arrIds = array();
foreach ($doc->getElementsByTagName('SequenceId') as $sid) $arrIds[] = $sid->nodeValue;
echo implode(',', $arrIds);
这假设您的文件中只有一个列表!否则,您必须根据父节点(而不是全局文档)执行标记查找。
希望这有帮助!
答案 1 :(得分:1)
我在这里看到几件事。首先,您的XML格式不正确。您的PropertyDetails标记未关闭。如此接近,而不是使用DOMDocument,使用SimpleXMLElement类。
首先,你的XML需要像这样纠正:
<?xml version="1.0" encoding="UTF-8"?>
<PropertyDetails ID="13953882" LastUpdated="Thu, 09 Jan 2014 01:43:48 GMT">
<ListingID>188691</ListingID>
<Board>117</Board>
<Address>
<StreetAddress>B LOCAL RD</StreetAddress>
<AddressLine1>B LOCAL RD</AddressLine1>
<City>PORT REXTON</City>
<Province>Newfoundland & Labrador</Province>
<PostalCode>A0C2H0</PostalCode>
<Country>Canada</Country>
</Address>
<Photo>
<PropertyPhoto>
<SequenceId>1</SequenceId>
</PropertyPhoto>
<PropertyPhoto>
<SequenceId>12</SequenceId>
</PropertyPhoto>
</Photo>
<ViewType>Ocean view</ViewType>
</PropertyDetails>
注意最后一行。
现在使用SimpleXMLElement,您将接近访问所需的方式。
$s = new SimpleXMLElement($fsp);
echo $s->Board;
echo $s->Address->City;
$sequence_ids = array();
foreach($s->Photo->PropertyPhoto as $PropertyPhoto)
$sequence_ids[] = $PropertyPhoto->SequenceId;
echo implode(',',$sequence_ids);
由于您是XML中的根节点,因此无需通过 - &gt; PropertyDetails [0]访问它。它知道。
希望这有帮助。