이 텍스트 및 XML 서버 응답을 PHP로 구문 분석하는 쉬운 방법이 있습니까?
-
29-10-2019 - |
문제
PHP를 사용하고 있으며이 서버 응답이 순수한 XML이 아니기 때문에 응답을 사용하기 위해 변수/배열로 바꾸려고 노력하고 있습니다.
XML 트리에 포함 된 변수에만 관심이 있습니다. 여러 컨테이너가있을 수 있으며 의지는 수량도 다릅니다. 또한 다양한 것들과 함께 더 "둥지"가있을 수도 있습니다 (나는 믿습니다).
서버 응답 예 :
HTTP/1.1 200 OK
Date: Wed, 07 Dec 2011 01:02:01 GMT
Server: Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8e DAV/2 PHP/5.2.17
X-Powered-By: PHP/5.2.17
Cache-Control: no-store, no-cache, no-transform, must-revalidate, private
Expires: 0
Vary: Accept-Encoding,User-Agent
Content-Length: 90
Connection: close
Content-Type: text/xml
<?xml version="1.0" encoding="UTF-8"?>
<response>
<var1>AAA</var1>
<var2>BBB</var2>
<var3>CCC</var3>
</response>
감사해요.
해결책
function xml2array($xml) {
$xmlary = array();
$reels = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*)<\/\s*\\1\s*>)/s';
$reattrs = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';
preg_match_all($reels, $xml, $elements);
foreach ($elements[1] as $ie => $xx) {
$xmlary[$ie]["name"] = $elements[1][$ie];
if ($attributes = trim($elements[2][$ie])) {
preg_match_all($reattrs, $attributes, $att);
foreach ($att[1] as $ia => $xx)
$xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia];
}
$cdend = strpos($elements[3][$ie], "<");
if ($cdend > 0) {
$xmlary[$ie]["text"] = substr($elements[3][$ie], 0, $cdend - 1);
}
if (preg_match($reels, $elements[3][$ie]))
$xmlary[$ie]["elements"] = xml2array($elements[3][$ie]);
else if ($elements[3][$ie]) {
$xmlary[$ie]["text"] = $elements[3][$ie];
}
}
return $xmlary;
}
다른 팁
당신은 이와 같은 일을 사용할 수 있습니다 strstr();
$h = 'HTTP/1.1 200 OK
Date: Wed, 07 Dec 2011 01:02:01 GMT
Server: Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8e DAV/2 PHP/5.2.17
X-Powered-By: PHP/5.2.17
Cache-Control: no-store, no-cache, no-transform, must-revalidate, private
Expires: 0
Vary: Accept-Encoding,User-Agent
Content-Length: 90
Connection: close
Content-Type: text/xml
<?xml version="1.0" encoding="UTF-8"?>
<response>
<var1>AAA</var1>
<var2>BBB</var2>
<var3>CCC</var3>
</response>';
print_r(strstr($h, "<?xml"));
// or this even strstr($h, '<?xml version="1.0" encoding="UTF-8"?>'
이것은 당신에게 원시 XML을 반환 할 것입니다.
<?xml version="1.0" encoding="UTF-8"?>
<response>
<var1>AAA</var1>
<var2>BBB</var2>
<var3>CCC</var3>
</response>
PHP 5를 사용하는 경우 SimpleXML 라이브러리를 사용하여 XML 문자열에서 객체를 만듭니다.
제휴하지 않습니다 StackOverflow