需要PHP脚本来解析此XML并将“ID”作为条件

时间:2012-04-26 06:55:23

标签: php xml parsing xml-parsing parser-generator

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Catalog SYSTEM "http://store.yahoo.com/doc/dtd/Catalog.dtd">
<Catalog StoreID="yhst-34564052343" StoreName="test.com" PublishTimestamp="1332786206">
<Item ID="10170090" TableID="yd-item">
<ItemField TableFieldID="more-image3" Value="test1"/>
<ItemField TableFieldID="price-range" Value="23"/>
<ItemField TableFieldID="more-image4" Value="test2"/>
<ItemField TableFieldID="name" Value="Liquid Light Drop 1 Pendant Light"/>
</Item>
 <Item ID="10170191" TableID="yd-item">
<ItemField TableFieldID="more-image3" Value="test3"/>
<ItemField TableFieldID="price-range" Value="34"/>
<ItemField TableFieldID="more-image4" Value="test4"/>
<ItemField TableFieldID="name" Value="Liquid Light Drop 4 Pendant Light"/>
</Item>
</Catalog>

我需要输出,如果ID 10170191通过,那么输出如下所示:

more-image3:-test3
price-range:-34
more-image4:-test4
name:-Liquid Light Drop 4 Pendant Light

1 个答案:

答案 0 :(得分:0)

试试这个:

<?php
$xml='<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Catalog SYSTEM "http://store.yahoo.com/doc/dtd/Catalog.dtd">
<Catalog StoreID="yhst-34564052343" StoreName="test.com" PublishTimestamp="1332786206">
<Item ID="10170090" TableID="yd-item">
<ItemField TableFieldID="more-image3" Value="test1"/>
<ItemField TableFieldID="price-range" Value="23"/>
<ItemField TableFieldID="more-image4" Value="test2"/>
<ItemField TableFieldID="name" Value="Liquid Light Drop 1 Pendant Light"/>
</Item>
 <Item ID="10170191" TableID="yd-item">
<ItemField TableFieldID="more-image3" Value="test3"/>
<ItemField TableFieldID="price-range" Value="34"/>
<ItemField TableFieldID="more-image4" Value="test4"/>
<ItemField TableFieldID="name" Value="Liquid Light Drop 4 Pendant Light"/>
</Item>
</Catalog>';

$xml=simplexml_load_string( $xml );
$xpath=$xml->xpath( '//Catalog/Item[@ID="10170191"]' );
foreach( $xpath as $result ) {
    foreach( $result->ItemField as $path ) {
        echo $path['TableFieldID'] . ': ' . $path['Value'] . '<br />';
    }
}
?>

希望这有帮助。