문제

이와 같은 XML이 있다고 가정 해 봅시다

<channel>
  <item>
    <title>This is title 1</title>
  </item>
</channel>

아래 코드는 제목을 문자열로 출력한다는 점에서 내가 원하는 것을 수행합니다.

$xml = simplexml_load_string($xmlstring);
echo $xml->channel->item->title;

여기 내 문제가 있습니다. 아래 코드는 해당 컨텍스트에서 제목을 문자열로 취급하지 않으므로 문자열 대신 배열에 SimpleXML 객체로 끝납니다.

$foo = array( $xml->channel->item->title );

나는 이런 식으로 일하고있다

$foo = array( sprintf("%s",$xml->channel->item->title) );

그러나 그것은 추악한 것 같습니다.

컨텍스트에 관계없이 SimpleXML 객체를 문자열로 강제하는 가장 좋은 방법은 무엇입니까?

도움이 되었습니까?

해결책

simplexmlobject를 문자열로 typecast :

$foo = array( (string) $xml->channel->item->title );

위의 코드는 내부적으로 호출됩니다 __toString() Simplexmlobject에서. 이 방법은 SimplexmloBject의 매핑 구성표를 방해하므로 공개적으로 사용할 수 없지만 위의 방식으로 여전히 호출 할 수 있습니다.

다른 팁

PHP 기능을 사용할 수 있습니다

strval();

이 함수는 전달 된 매개 변수의 문자열 값을 반환합니다.

기본 SimpleXML 메소드가 있습니다 SimplexmlElement :: ASXML매개 변수에 따라 XML 1.0 파일에 SimplexMlElement를 쓰거나 문자열에 작성합니다.

$xml = new SimpleXMLElement($string);
$validfilename = '/temp/mylist.xml';
$xml->asXML($validfilename);    // to a file
echo $xml->asXML();             // to a string

그것을하는 또 다른 추악한 방법 :

$foo = array( $xml->channel->item->title."" );

작동하지만 예쁘지는 않습니다.

XML 데이터를 PHP 배열로 가져 오려면 다음을 수행합니다.

// this gets all the outer levels into an associative php array
$header = array();
foreach($xml->children() as $child)
{
  $header[$child->getName()] = sprintf("%s", $child); 
}
echo "<pre>\n";
print_r($header);
echo "</pre>";

아이를 키우려면 다음을 수행하십시오.

$data = array();
foreach($xml->data->children() as $child)
{
  $header[$child->getName()] = sprintf("%s", $child); 
}
echo "<pre>\n";
print_r($data);
echo "</pre>";

원하는 것을 얻을 때까지 각 레벨을 통해 $ xml->을 확장 할 수 있습니다. 모든 노드를 레벨없이 또는 원하는 다른 방식으로 하나의 배열에 넣을 수도 있습니다.

허용 된 답변은 실제로 문자열이 포함 된 배열을 반환합니다. 이는 OP가 요청한 것 (문자열)이 아닙니다. 해당 답변을 확장하려면 사용하십시오.

$foo = [ (string) $xml->channel->item->title ][0];

배열의 단일 요소 인 문자열을 반환합니다.

strval을 시도하십시오 ($ xml-> 채널-> 항목-> 제목)

그들이 가시성을 변경했는지 확실하지 않습니다 __toString() 수락 된 답변이 작성되었으므로 현재로서는 나에게 잘 작동합니다.

var_dump($xml->channel->item->title->__toString());

산출:

string(15) "This is title 1"

기본 simplexml 방법 SimplexmlElement :: ASXML 매개 변수에 따라 XML 1.0 파일에 SimpleXmlElement를 작성합니다.

$get_file= read file from path;
$itrate1=$get_file->node;
$html  = $itrate1->richcontent->html;


echo  $itrate1->richcontent->html->body->asXML();
 print_r((string) $itrate1->richcontent->html->body->asXML());

다음은 모든 단일 자식 요소를 String:

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FUNCTION - CLEAN SIMPLE XML OBJECT
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function cleanSimpleXML($xmlObject = ''){

    // LOOP CHILDREN
    foreach ($xmlObject->children() as $child) {

        // IF CONTAINS MULTIPLE CHILDREN
        if(count($child->children()) > 1 ){

            // RECURSE
            $child = cleanSimpleXML($child);

        }else{

            // CAST
            $child = (string)$child;

        }

    }

    // RETURN CLEAN OBJECT
    return $xmlObject;

} // END FUNCTION
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top