XML:XML PHP讓孩子們珍惜
<Result xmlns="" xmlns:xsi="" totalResultsAvailable="0" totalResultsReturned="0" schk="true" totalLooseOffers="0" xsi:schemaLocation="">
<details>
<ID></ID>
<applicationVersion>1.0</applicationVersion>
<applicationPath/>
<date>2016-05-23T12:17:16.369-03:00</date>
<elapsedTime>17</elapsedTime>
<status>success</status>
<message>success</message>
</details>
<category id="1">
<thumbnail url="http://image.google.com/test.jpg"/>
<links>
<link url="www.google.com" type="category"/>
<link url="www.google2.com" type="xml"/>
</links>
<name>Category</name>
<filters>
<filter id="1" name="Filter1">
<value id="1" value="Test1"/>
<value id="2" value="Test2"/>
<value id="3" value="Test3"/>
</filter>
<filter id="2" name="Filter2">
<value id="1" value="Test4"/>
<value id="2" value="Test5"/>
<value id="3" value="Test6"/>
</filter>
</filters>
</category>
</Result>
PHP:
$xml = simplexml_load_file("http://xml.com");
foreach($xml->category->filters as $filters){
foreach($filters->children() as $child){
echo $child['value'];
}
}
我試圖讓過濾器值,但沒有顯示的代碼,我有。我看到了有關xpath的一些信息,但不知道它是否適用於這種情況。你有任何線索嗎?
-
當XML看起來是這樣的:
<Result xmlns="" xmlns:xsi="" totalResultsAvailable="0" totalResultsReturned="0" schk="true" totalLooseOffers="0" xsi:schemaLocation="">
<details>
<ID></ID>
<applicationVersion>1.0</applicationVersion>
<applicationPath/>
<date>2016-05-23T12:17:16.369-03:00</date>
<elapsedTime>17</elapsedTime>
<status>success</status>
<message>success</message>
</details>
<subCategory id="1">
<thumbnail url="http://image.google.com/test.jpg"/>
<name>Subcategory</name>
</subCategory>
<subCategory id="2">
<thumbnail url="http://image.google.com/test2.jpg"/>
<name>Subcategory2</name>
</subCategory>
</Result>
然後我能夠做到這一點:
foreach($xml->subCategory as $subCategory){
$categoryId = $subCategory['id'];
$categoryName = $subCategory->name;
}
的SimpleXML存儲在對象變量中的XML根節點,所以'$ xml'你的情況直接指''節點。你應該使用'foreach($ xml-> filters作爲$ filters)'而不是'$ xml-> category-> filters'參見http://stackoverflow.com/questions/17367434/xml-simplexml-load-file- foreach-not-looping/17367513#17367513 –
好吧@MichaelBerkowski我不知道這件事。我的xml開頭爲:「 」。這是根嗎?因爲我改變了你的建議,並且還沒有顯示 –
如果因爲''確實是根,所以如果有額外的父節點環繞'',請編輯你的帖子以顯示完整的XML結構。如果結果不同,我會重新提出這個問題。 –