使用PHP中的子值获取xml文档的祖先节点

时间:2014-03-05 07:26:38

标签: php xml foreach simplexml

对于此节点

<product>
    <productId>531334</productId>
    <productName>Mixed wrap platter - </productName>
    <productImage>http://d25hqtnqp5nl24.cloudfront.net/images/products/9/LN_531334_BP_9.jpg</productImage>
    <productUrl>http://www.waitrose.com/shop/DisplayProductFlyout?productId=75117&amp;?utm_source=infectious&amp;utm_medium=display&amp;utm_campaign=baby</productUrl>
    <price>16.00</price>
    <categoryid1>Groceries</categoryid1>
    <categoryid2>Fresh</categoryid2>
    <categoryid3>Fresh Party Food to Order</categoryid3>
</product>

如何根据子categoryid2的值获取整个产品节点?

1 个答案:

答案 0 :(得分:0)

yoiu可以尝试使用SimpleXMLElement类:

$xml_string = '<product>
        <productId>531334</productId>
        <productName>Mixed wrap platter - </productName>
        <productImage>http://d25hqtnqp5nl24.cloudfront.net/images/products/9/LN_531334_BP_9.jpg</productImage>
        <productUrl>http://www.waitrose.com/shop/DisplayProductFlyout?productId=75117&amp;?utm_source=infectious&amp;utm_medium=display&amp;utm_campaign=baby</productUrl>
        <price>16.00</price>
        <categoryid1>Groceries</categoryid1>
        <categoryid2>Fresh</categoryid2>
        <categoryid3>Fresh Party Food to Order</categoryid3>
    </product>';

    $xml = new SimpleXMLElement($xml_string);
    foreach ($xml->product as $p){
        echo'<p>productID: '.$p->productId.'</p>';
        //you can do it for every value inside product
    }