2011-02-19 136 views
3

我正在嘗試使用PHP的SimpleXML解析工作源。我以前只使用JSON,並且在解析器工作時遇到問題。下面是一些樣本數據:用PHP解析XML

<shrs> 
    <rq url="http://api.simplyhired.com/a/jobs-api/xml_v2/q-comission"> 
     <t>Comission Jobs</t> 
     <dt>2011-02-18T23:58:38Z</dt> 
     <si>0</si> 
     <rpd>10</rpd> 
     <tr>192</tr> 
     <tv>146</tv> 
     <em url=""/> 
     <h> 
      <kw pos="1"/> 
     </h> 
    </rq> 
    <rs> 
     <r> 
      <jt>Virtual Recruiter (IT) - Comission ...</jt> 
      <cn url="">Remedy Intelligent Staffing</cn> 
      <src url="http://api.simplyhired.com/a/job-details/view/jobkey-monster91949932/cjp-0/hits-192?aff_id=28700">Monster</src> 
      <ty>organic</ty> 
      <loc cty="Buffalo" st="NY" postal="14211" county="" region="" country="US">Buffalo, NY</loc> 
      <ls>2011-02-04T05:51:17Z</ls> 
      <dp>2011-02-04T05:51:17Z</dp> 
      <e> 
    Seeking a candidate with previous recruiting experience to work as a Virtual Recruiter for a large client in the IT industry.a Responsibilities: Will recruit, screen, interview, and place candidates for many openings throughout the US Will... 
    </e> 
     </r> 
     <r> 
      <jt>Virtual Loan Officer (Mortgage) draw vs comission</jt> 
      <cn url="">Netbranchology.com</cn> 
      <src url="http://api.simplyhired.com/a/job-details/view/jobkey-7114.353281/cjp-2/hits-192?aff_id=28700">netbranchology.com</src> 
      <ty>organic</ty> 
      <loc cty="Denver" st="CO" postal="80218" county="" region="" country="US">Denver, CO</loc> 
      <ls>2011-02-10T11:47:50Z</ls> 
      <dp>2011-01-26T11:36:18Z</dp> 
      <e> 
    Minimize your overhead by becoming a virtual loan officer... Our client, a Texas-based mortgage banker, has just launched an innovative new program that lets you work from anywhere to originate residential mortgage loans. No office is... 
    </e> 
     </r> 
    </rs> 
</shrs> 

[ETC]

我想通過下處理它的每個作業結果來檢索標籤的元數據到變量,然後循環。我怎樣才能用PHP做到這一點? (我一直在用SimpleXML函數玩耍至今)

回答

2

節點作爲對象屬性訪問,屬性使用數組表示法。使用foreach可以迭代節點。您可以通過將其轉換爲字符串來獲取節點的內容。 (所以如果你使用echo暗示)

$shrs = simplexml_load_string($xml); 

foreach ($shrs->rs->r as $r) 
{ 
    $jobTitle = $r->jt; 
    $city = $r->loc['cty']; 

    echo "There's an offer for $jobTitle in $city<br />\n"; 
} 
1

嘗試的SimpleXML:http://www.php.net/manual/en/book.simplexml.php

它會分析你的XML到一個不錯的對象。

編輯:這裏是如何使用它(假設你的XML存儲在變量$ XML):

$xmlObject = new SimpleXMLElement($xml); 

// to retrieve "http://api.simplyhired.com/a/jobs-api/xml_v2/q-comission" 
$url = $xmlObject->rq['url']; 

// to retrieve "Comission Jobs" 
$t = $xmlObject->rq->t; 
... 

希望它能幫助。

+0

等等,當時他發佈了他說的EasyXML的問題。我想他犯了一個錯誤,然後編輯它。 – 2011-02-19 05:43:22

+0

我輸入了Easy而不是Simple,這是我第一次使用這個庫。謝謝你,克里斯蒂安! – MarathonStudios 2011-02-19 08:56:53