我正在使用 Linkedin API --> https://developer.linkedin.com/documents/profile-fields#company
一切正常,我可以毫无问题地连接到 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] => 0123456
[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
)
)
)
)
现在我的问题:
如何仅检索和打印 [recommendation-text] 节点?我已经只调用了收到的建议,$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。