2014-03-24 268 views
1

我在PHP中使用simplexml_load_file函數來遍歷一個xml文件。PHP如何通過屬性名稱獲取SimpleXMLElement對象元值?

我卡在這個意義上,我試圖訪問一個particulr元對象的值,但不知道如何這樣做。

此代碼有效,但不是每個xml文件都是相同的,所以我希望能夠通過名稱獲得主題值的某種方式。

<?php 
$file = simplexml_load_file('test.xml'); 

$subject = $file->head->meta[1][content]; 

print($subject); 
?> 

所以基本上我可以用$file->head->meta[1][content]遍歷右到$主題,但就像我說的,這並不總是可行的。

在Python中,我會使用類似subject = self.element.find(".//meta[@name='subject']/ @content")

下面是一些XML我解析的例子:

<?xml version="1.0" encoding="windows-1252"?> 
<nitf> 
    <head> 
    <meta name="ProgramVersion" content="2.0"/> 
    <meta name="subject" content="XML test nonjump"/> 
    <meta name="Category" content="Business"/> 
    <meta name="Priority" content="Inside"/> 
    <meta name="Format" content="3cB"/> 
    <meta name="AuthorID" content="532944370"/> 
    <ads/> 
    <docdata> 
     <correction id-string="401"/> 
     <urgency ed-urg="7"/> 
     <date.release norm="2014-03-21T00:01:00-07:00"/> 
     <doc.copyright year="2014" holder="APWire"/> 
     <date.expire norm="2014-04-18T12:01:00-07:00"/> 
     <identified-content/> 
    </docdata> 
    </head> 
    <body> 
    <body.head> 
     <hedline> 
     <hl1 style="@Hed Benton">Test: British unemployment stays at 7.2 percent reinforcing BOE guidance message</hl1> 
     </hedline> 
     <byline> 
     <p style="@Byline">By Test User</p> 
     <p style="@Byline2">Bloomberg News</p> 
     </byline> 
    </body.head> 
    <body.content> 
     <block> 
     <p style="@Subhed 1 col" lede="true">Repeating to correct keyword</p> 
     <p style="@Body justified">LONDON — Britain’s unemployment rate held steady in the three months through January, reinforcing the Bank of England’s case for keeping interest rates at a record low.</p> 
     <p style="@Body justified">The jobless rate measured by International Labour Organization methods was 7.2 percent, the same as in the final quarter of 2013 the Office for National Statistics said in London Wednesday. That’s in line with the median forecast in a Bloomberg survey. Jobless claims - a narrower measure of unemployment, fell 34,600, more than economists had forecast, and wage growth accelerated.</p> 
     <p style="@Body justified">The figures hand ammunition to BOE Governor Mark Carney’s argument that officials should be in no hurry to increase borrowing costs. Rapid falls in unemployment last year forced the BOE to abandon the 7 percent threshold for considering a rate increase. Policy makers said last month they’re now focused on a broader range of measures of spare capacity.</p> 
     </block> 
    </body.content> 
    </body> 
</nitf> 

回答

1

你在Python起訴「的XPath」,它也可在SimpleXML中。

$result = $element->xpath(".//meta[@name='subject']/ @content"); 

文檔是在這裏:http://www.php.net/manual/en/simplexmlelement.xpath.php

+0

良好的通話。我最終不得不使用'$ subject = $ file-> xpath(「.// meta [@ name ='subject']/@content」)[0] ['content']; ' – bigmike7801