2012-04-16 104 views
0

我正在使用Linkedin API - > https://developer.linkedin.com/documents/profile-fields#company如何使用simplexmlelement或其他XML函數從數組中檢索節點?

一切工作正常,我可以連接到API沒有問題。當我請求一些數據時,貝婁遵循API返回的數據。

這是我的要求(我不會發布整個代碼,它超過500行),但它是我想要檢索的本質。

$response2 = $OBJ_linkedin->profile('~:(recommendations-received)'); 
if($response2['success'] === TRUE) 
{ 
    $response2['linkedin'] = new SimpleXMLElement($response2['linkedin']); 
    echo "<pre>" . print_r($response2['linkedin'], TRUE) . "</pre>"; 
} 
else 
{ 
    // request failed 
    echo "Error: <br />RESPONSE:<br /><br /><pre>" . print_r($response2) . "</pre>"; 
} 

按照上述迴應:

SimpleXMLElement Object 
(
    [recommendations-received] => SimpleXMLElement Object 
     (
      [@attributes] => Array 
       (
        [total] => 1 
       ) 

      [recommendation] => SimpleXMLElement Object 
       (
        [id] =>
        [recommendation-type] => SimpleXMLElement Object 
         (
          [code] => service-provider 
         ) 

        [recommendation-text] => Here come the recommendation text from the API. 
        [recommender] => SimpleXMLElement Object 
         (
          [id] => npAnFGrTys 
          [first-name] => John 
          [last-name] => Doe 
         ) 

       ) 

     ) 

) 

現在我的問題:

如何檢索並打印[推薦文本]節點?我已經只打電話給推薦了 - 收到了$response2 = $OBJ_linkedin->profile('~:(recommendations-received)');但它返回了整個事情,那麼如何獲得只有[recommendation-text] ???

我嘗試使用simplexmlelement(http://br2.php.net/manual/en/class.simplexmlelement.php),但沒有成功。

在此先感謝您的任何幫助。

[結果]

,我將發佈什麼是工作給我看答案。

我用下面的代碼的建議@Mircea:

$sxml = new SimpleXMLElement($response2['linkedin']); 
$res = $sxml->xpath('recommendations-received/recommendation/recommendation-text'); 
echo $res[0]; 

,而不是驗證碼:

$response2['linkedin'] = new SimpleXMLElement($response2['linkedin']); 
    echo "<pre>" . print_r($response2['linkedin'], TRUE) . "</pre>"; 

這裏的區別是,現在我使用XPath的方法來搜索simpleXML節點爲兒童匹配。謝謝@Mircea。

回答

2

您應該嘗試simplexmlelement http://www.php.net/manual/en/simplexmlelement.xpath.php的xpath函數。我認爲corect方式得到你想要的是:

$sxml->xpath('recommendations-received/recommendation/recommendation-text') 

它返回一個數組,所以你應該在它遍歷(看該網頁上的例子)。 xpath查詢就像這樣,它最終取決於接收到的xml的結構。

希望它有幫助。

+0

你是對的人! $ sxml = new SimpleXMLElement($ response2 ['linkedin']); $ res = $ sxml-> xpath('recommendations-received/recommendation/recommendation-text'); echo $ res [0]; – B4NZ41 2012-04-16 17:24:04

+0

我會接受你的答案作爲正確的答案!非常感謝你,這很簡單,我無法想象。再次感謝您澄清這個想法! – B4NZ41 2012-04-16 17:25:59

+0

沒問題。很高興能有幫助 – Mircea 2012-04-16 19:16:12

0

訪問recommendation-text屬性將通過什麼來完成,如:

foreach($response2->{recommendations-received} as $recommendation) { 
    $recommendation->{recommendation-text} 
} 
+0

我無法檢索這樣做。這裏不行。什麼都沒發生。 :( – B4NZ41 2012-04-16 17:17:30

+0

無論如何,答案是在使用xpath方法來搜索節點。 – B4NZ41 2012-04-16 17:35:35

相關問題