2016-10-18 6 views
1

xml을 객체로 변환하면 print_r($result);에 따라 모든 것이 잘 보입니다. 내가 $result->title를 사용하는 경우 그러나 개체 대신 문자열을 반환PHP - simplexml_load_string이 예상대로 작동하지 않습니다.

$xml = '<return> 
    <id>65510</id> 
    <title>SMART</title> 
    <info/> 
    <documents> 
    <name>file_1.pdf</name> 
    <path>http://www.domain.com/documents/file_1.pdf</path> 
    </documents> 
    <documents> 
    <name>file_2.pdf</name> 
    <path>http://www.domain.com/documents/file_2.pdf</path> 
    </documents> 
    <documents> 
    <name>file_3.pdf</name> 
    <path>http://www.domain.com/documents/file_3.pdf</path> 
    </documents> 
</return>'; 

$result = simplexml_load_string($xml); 
print_r($result); /* returns: 

SimpleXMLElement Object 
(
    [id] => 65510 
    [title] => SMART 
    [info] => SimpleXMLElement Object 
     (
     ) 

    [documents] => Array 
     (
      [0] => SimpleXMLElement Object 
       (
        [name] => file_1.pdf 
        [path] => http://www.domain.com/documents/file_1.pdf 
       ) 

      [1] => SimpleXMLElement Object 
       (
        [name] => file_2.pdf 
        [path] => http://www.domain.com/documents/file_2.pdf 
       ) 

      [2] => SimpleXMLElement Object 
       (
        [name] => file_3.pdf 
        [path] => http://www.domain.com/documents/file_3.pdf 
       ) 

     ) 

) 
*/ 
$_VALUE['title'] = $result->title; 
print_r($_VALUE); /* returns: 

Array 
(
    [title] => SimpleXMLElement Object 
     (
      [0] => SMART 
     ) 

) 
*/ 

foreach ($result->documents as $key=>$value) { 
echo $key . "<br/>"; 
} /* returns: 

documents 
documents 
documents 

instead of returning: 
1 
2 
3 
*/ 

정말 이상한 얻을 $result->documents을 .. 루핑 때 인덱스 1,2,3와 배열로 문자열과 $result->documents을 반환 $result->title이 필요합니다.

답변

1

여기서는 print_recho 사이에 차이가 있습니다. 대신 인쇄

echo (string) $result->title; 

그것은 SMART

및 배열

$p = 1; 
foreach ($result->documents as $value) { 
    echo $value->name . "<br/>"; 
    //for key 
    echo $p++.'</br>'; 
} 
+0

확인로 작동 출력됩니다 에코 시도,하지만 난 PHPMailer에서이 값을 사용하고이 오류가 발생합니다 : 치명적인 오류 : catch되지 않은 예외 ' 예외 'with message' 'SimpleXMLElement'의 직렬화가 허용되지 않습니다. ' – Totallama

+0

'그렇다면 내부적으로 모두 'SimpleXMLElement'이기 때문에 case 데이터를'string'으로 입력해야합니다. 따라서'echo (string) $ result-> title ; ' –

+0

그리고 무엇 배열 어때? – Totallama