2013-07-22 2 views
0

xml 문서를 구문 분석/읽는 중 잘못 알고 있습니다. 내 생각 엔 표준화되지 않았기 때문에 문자열에서 아무 것도 읽지 않으려면 다른 프로세스가 필요합니다.PHP - 구문 분석, XML 읽기

그렇다면 나는 누군가가 xml을 읽는 방법을 배우는 데 오히려 기뻐합니다. 다음은 내가 가지고있는 것과 내가하고있는 것입니다.

example.xml 내가 다시 print_r에서 어떤 결과를 얻기없는거야

<?php 
$content = 'example.xml'; 
$string = file_get_contents($content); 
$xml = simplexml_load_string($string); 
print_r($xml); 
?> 

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="someurl.php"?> 
<response> 
<status>Error</status> 
<error>The error message I need to extract, if the status says Error</error> 
</response> 

read_xml.php.
내가 좋아하는 뭔가 더 표준에 xml 전환 :

<?xml version="1.0" encoding="ISO-8859-1"?> 
<note> 
<to>Tove</to> 
<from>Jani</from> 
<heading>Reminder</heading> 
<body>Don't forget me this weekend!</body> 
</note> 

... 그리고 그것을 잘 작동했다. 그래서 비표준 형식 때문일 거라고 확신합니다. 원본에서 되돌려 보겠습니다.

<status><error> 태그를 어떻게 추출합니까?

답변

0

테크는 좋은 대답을 가지고 있지만, 당신은 SimpleXML을 사용하려는 경우, 당신은이 같은 시도 할 수 있습니다 :

<?php 

$xml = simplexml_load_file('example.xml'); 
echo $xml->asXML(); // this will print the whole string 
echo $xml->status; // print status 
echo $xml->error; // print error 

?> 

수정 : XML에 <status><error> 태그가 여러 개있는 경우 다음을 확인하십시오.

$xml = simplexml_load_file('example.xml'); 
foreach($xml->status as $status){ 
    echo $status; 
} 
foreach($xml->error as $error){ 
    echo $error; 
} 

나는 루트가 <response>이라고 가정합니다. 그렇지 않은 경우 $xml->response->status$xml->response->error을 시도하십시오.

0

저는 PHP의 DOMDocument 클래스를 더 선호합니다. 이 같은

시도 뭔가 :

<?php 

$xml = '<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="someurl.php"?> 
<response> 
<status>Error</status> 
<error>The error message I need to extract, if the status says Error</error> 
</response>'; 

$dom = new DOMDocument(); 
$dom->loadXML($xml); 

$statuses = $dom->getElementsByTagName('status'); 
foreach ($statuses as $status) { 
    echo "The status tag says: " . $status->nodeValue, PHP_EOL; 
} 
?> 

데모 : http://codepad.viper-7.com/mID6Hp