2
我從一個API的XML響應如下:回聲XML子節點的值
$response = <<<XML
<response uri="/crm/private/xml/Leads/insertRecords">
<result>
<message>Record(s) updated successfully</message>
<recorddetail>
<fl val="Id">1203498000000109001</fl>
<fl val="Created Time">2014-09-24 09:19:44</fl>
<fl val="Modified Time">2014-09-24 11:38:08</fl>
<fl val="Created By"><!--[CDATA[Brydges]]--></fl>
<fl val="Modified By"><!--[CDATA[Brydges]]--></fl>
</recorddetail>
</result>
</response>
XML;
如果我想要的消息,這似乎很容易使用
$xml_response = new SimpleXMLElement($response); $message = $xml_response->result->message; echo $message;
但是,我試圖檢索<fl val="id">
行的內容,例如1203498000000109001.
我已經看過許多問題上的SO,並嘗試了所有那些建議,但沒有成功如下:
//using xpath with SimpleXMLElement
$xml_response = new SimpleXMLElement($response);
$zoho_id = $xml_response->xpath('/response/result/recorddetail/fl[@val="Id"]');
echo $zoho_id;
//using xpath with simplexml_load_string
$xml_response = new simplexml_load_string($response);
$zoho_id = $xml_response->xpath('/response/result/recorddetail/fl[@val="Id"]');
echo $zoho_id;
//using a foreach loop
$xml_response = new SimpleXMLElement($response);
foreach ($xml_response->result->recorddetail->fl as $fl) {
if ((string) $fl['val'] == 'Id') {
echo (string) $fl;
}
}
// using a foreach loop and then a switch case over the val attribute value to only echo Id
foreach ($xml_response->result->recorddetail->fl as $fl) {
switch((string) $fl['val']) { // Get attributes as element indices
case 'Id':
echo (string)$fl, ' is the Id';
break;
}
}
任何建議如何我可以檢索我需要的內容?
FOLLOWING GHOSTS的建議:
的print_r($ DOC)返回:
SimpleXMLElement Object (
[@attributes] => Array (
[uri] => /crm/private/xml/Leads/insertRecords
)
[result] => SimpleXMLElement Object (
[message] => Record(s) updated successfully
[recorddetail] => SimpleXMLElement Object (
[FL] => Array (
[0] => 1203498000000109001
[1] => 2014-09-24 09:19:44
[2] => 2014-09-24 13:06:37
[3] => SimpleXMLElement Object (
[@attributes] => Array (
[val] => Created By
)
)
[4] => SimpleXMLElement Object (
[@attributes] => Array (
[val] => Modified By
)
)
)
)
)
)
感謝鬼。然而,第一個例子打破了整個腳本(似乎是根據Dreamweaver驗證在最後做的[0],第二個也不行,我恐怕也是。 另外,如果我將[0]從第一個例子,然後嘗試以下我得到意想不到的結果: '$ xml_response = new SimpleXMLElement($ response); $ zoho_id =(string)$ xml_response-> xpath('/ response/result/recorddetail/fl [@val =「Id」]'); var_dump($ zoho_id);' – JBReading 2014-09-24 12:37:24
@JB閱讀很好基於你的例子,這是工作的一個,在這裏[檢查演示](http://codepad.viper-7.com/Etav19) – Ghost 2014-09-24 12:42:48
@JBReading除非當然(這沒有意義)你發佈在我測試的問題上的那個不是你正在使用的xml – Ghost 2014-09-24 12:43:50