>  기사  >  백엔드 개발  >  PHP XML을 배열로

PHP XML을 배열로

王林
王林원래의
2024-08-29 13:09:58923검색

우리는 이를 사용하여 XML 문서를 PHP 배열로 변환합니다. 때로는 XML 문서를 수신 데이터로 처리하거나 데이터를 XML 문서로 내보내야 하는 경우가 있습니다. XML 언어는 웹사이트나 애플리케이션 전반에 걸쳐 데이터 공유를 구성하는 데 사용됩니다. 따라서 XML 데이터와 원활하게 작동할 수 있도록 배열 작업에 XML을 제공합니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

변환하는 동안 아래와 같은 몇 가지 기능을 사용해야 합니다 –

  • file_get_contents() 함수: 이 함수는 파일을 문자열로 읽어옵니다.
  • simplexml_load_string() 함수: 이 함수는 XML을 구문 분석하고 객체를 반환하는 데 사용됩니다.
  • json_encode() 함수: 이 함수는 JSON 문자열을 인코딩하고 JSON 값을 반환합니다.
  • json_decode() 함수: JSON 문자열(PHP 변수)을 디코딩하는 함수입니다.

PHP XML을 배열로 작업

XML 문서를 받아 배열로 변환합니다. ExXMl.xml이라는 XML 문서가 있다고 가정합니다. 이제 이를 배열로 변환하려고 합니다. 따라서 변환하려면 몇 가지 단계를 따라야 합니다 –

  1. file_get_content() 함수를 사용하여 ExXMl.xml 파일을 PHP로 가져오면 ExXMl.xml 파일을 문자열로 읽어 변수에 저장합니다.
  2. 다음으로, 읽어온 문자열 데이터를 simplexml_load_string() 함수를 이용해 객체로 변환합니다.
  3. 마지막으로 json_decode() 함수를 사용하여 json 문자열을 디코딩하면 json으로 인코딩된 문자열이 배열로 변환됩니다.

XML 파일을 로드하고 이를 PHP 배열로 변환하는 예 –

예시 #1

먼저 "ExXML.xml"이라는 이름으로 xml 데이터 파일을 생성하고 다음과 같이 데이터 콘텐츠를 생성합니다.

코드:

<?xml version="1.0" encoding="utf-8"?>
<Student>
<firstname name = 'John'>
<rollno> 12 </rollno>
<marks> 78 </marks>
<subject> English </subject>
</firstname>
<firstname name='Sam'>
<rollno> 15 </rollno>
<marks> 80 </marks>
<subject> English </subject>
</firstname>
<firstname name='Praveen'>
<rollno> 30 </rollno>
<marks> 50 </marks>
<subject> English </subject>
</firstname>
</Student>
Next,we create the PHP file to read and load the XML file, as below -
<?php
// xml file
$file = "ExXML.xml";
// Read XML file as string
$xml_file = file_get_contents($file);
//  xml string is Convert into an object
$obj = simplexml_load_string($xml_file);
// AN object Convert into json string
$json_string = json_encode($obj);
// Convert json string into an array
$array = json_decode($json_string, true);
// print an array
print_r($array);
?>

출력:

PHP XML을 배열로

열기 및 닫는 태그가 모두 적절합니다. 다음으로, 로드된 개체는 각각 json_encode() 및 json_decode() 함수의 도움을 받아 PHP 배열로 인코딩 및 디코딩됩니다.

예시 #2

오류가 발생하고 파싱되는 예-

다음으로 PHP XML을 배열로 이해하기 위해 PHP 코드를 작성하는데, 여기서 XML 태그 불일치나 구조가 올바르지 않아 XML을 배열로 수행하는 동안 발생한 구문 분석 오류를 아래와 같이 살펴보겠습니다 –

코드:

<?xml version='1.0'?>
<Student>
<firstname name = 'John'>
<rollno> 12 </rollno>
<marks> 78 </marks>
<!-- missing -->
</firstname>
<firstname name='Sanjay'>
<rollno> 15 </rollno>
<marks> 80 </marks>
<!-- mismatch tag -->
<subject> English <subject>
</firstname>
<firstname name='Parvez'>
<rollno> 30 </rollno>
<marks> 50 </marks>
<subject> English </subject>
</firstname>
</Student>
Next, we create the PHP file to read and load the XML file, as below -
<?php
// xml file
$file = "ExXML.xml";
// Read file as string
$xml_file = file_get_contents($file);
//  xml string is Convert into an object
$obj = simplexml_load_string($xml_file);
// check xml load or not
if ($obj == FALSE) {
echo "There were errors to parse the XML file.\n";
exit;
}
// AN object Convert into json string
$json_string = json_encode($obj);
// Convert json string into an array
$array = json_decode($json_string, true);
// print an array
print_r($array);
?>

출력:

PHP XML을 배열로

열기 태그와 닫는 태그 중 하나가 일치하지 않고 태그 중 하나가 누락되었습니다(주석 태그가 있는 XML 파일에 언급된 대로).  위 출력에서 ​​볼 수 있듯이 XML 파일을 구문 분석하고 로드하는 동안 경고가 발생합니다. 그러니 경고문을 읽어보시고 XML 파일을 수정하신 후 다시 로드해주세요.

위 내용은 PHP XML을 배열로의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:PHP XML 파서다음 기사:PHP XML 파서