當我使用 web 服務中的 simplexml_load_file 時,它??回傳
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.cebroker.com/CEBrokerWebService/"><licensees><licensee
valid="true" State="FL" licensee_profession="RN"
licensee_number="2676612" state_license_format="" first_name="HENRY"
last_name="GEITER" ErrorCode="" Message="" TimeStamp="2/19/2022
4:53:35 AM" /></licensees></string>
但是,我無法將其決議為 XML 來獲取屬性。我需要將其格式化為:
<licensees>
<licensee valid="true" State="FL" licensee_profession="RN" licensee_number="2676612" state_license_format="" first_name="HENRY" last_name="GEITER" ErrorCode="" Message="" TimeStamp="2/18/2022 6:43:20 PM" />
</licensees>
然后這段代碼有效:
$xml_string = simplexml_load_string($xmlresponse);
foreach ($xml_string->licensee[0]->attributes() as $a => $b) {
echo $a , '=' , $b;
}
我嘗試了 str_replace 和解碼,但沒有成功。
uj5u.com熱心網友回復:
“字串”元素的內容是一個 XML 檔案本身——存盤在一個文本節點中。你可以認為它是一個信封。因此,您必須先加載外部 XML 檔案并讀取文本內容,然后再次將其加載為 XML 檔案。
$outerXML = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.cebroker.com/CEBrokerWebService/"><licensees><licensee
valid="true" State="FL" licensee_profession="RN"
licensee_number="2676612" state_license_format="" first_name="HENRY"
last_name="GEITER" ErrorCode="" Message="" TimeStamp="2/19/2022
4:53:35 AM" /></licensees></string>
XML;
$envelope = new SimpleXMLElement($outerXML);
$licensees = new SimpleXMLElement((string)$envelope);
echo $licensees->asXML();
在 DOM 中:
$envelope = new DOMDocument();
$envelope->loadXML($outerXML);
$document = new DOMDocument();
$document->loadXML($envelope->documentElement->textContent);
echo $document->saveXML();
uj5u.com熱心網友回復:
由于您想要的 XML 似乎存盤為 htmlentities,因此您的第一個simplexml_load_string()不會將其讀取為 XML。如果您使用該字串并運行它,simplexml_load_string()那么您將獲得它作為 XML:
$xml_string = simplexml_load_string($xmlresponse);
$licensees = simplexml_load_string($xml_string);
var_dump($licensees);
輸出:
object(SimpleXMLElement)#2 (1) {
["licensee"]=>
object(SimpleXMLElement)#3 (1) {
["@attributes"]=>
array(10) {
["valid"]=>
string(4) "true"
["State"]=>
string(2) "FL"
["licensee_profession"]=>
string(2) "RN"
["licensee_number"]=>
string(7) "2676612"
["state_license_format"]=>
string(0) ""
["first_name"]=>
string(5) "HENRY"
["last_name"]=>
string(6) "GEITER"
["ErrorCode"]=>
string(0) ""
["Message"]=>
string(0) ""
["TimeStamp"]=>
string(21) "2/19/2022 4:53:35 AM"
}
}
}
這是一個演示:https ://3v4l.org/da3Up
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/430487.html
上一篇:使用awk替換xml標記值
