programing

컨텍스트에 관계없이 SimpleXML 개체를 문자열로 강제 적용

nasanasas 2020. 10. 23. 07:59
반응형

컨텍스트에 관계없이 SimpleXML 개체를 문자열로 강제 적용


이와 같은 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를 문자열로 타입 캐스트합니다.

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

위의 코드는 내부적으로 __toString()SimpleXMLObject를 호출 합니다. 이 메서드는 SimpleXMLObject의 매핑 체계를 방해하므로 공개적으로 사용할 수 없지만 위의 방식으로 호출 할 수 있습니다.


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

strval();

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


기본 SimpleXML 메소드 SimpleXMLElement :: asXML이 있습니다 . 매개 변수에 따라 SimpleXMLElement를 xml 1.0 파일 또는 문자열에만 기록합니다.

$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."" );

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


수락 된 답변은 실제로 OP가 요청한 문자열 (문자열)이 아닌 문자열을 포함하는 배열을 반환합니다. 그 대답을 확장하려면 다음을 사용하십시오.

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

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


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->을 확장 할 수 있습니다. 레벨없이 또는 원하는 다른 방식으로 모든 노드를 하나의 배열에 넣을 수도 있습니다.


strval ($ xml-> channel-> item-> title) 시도


Not sure if they changed the visibility of the __toString() method since the accepted answer was written but at this time it works fine for me:

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

OUTPUT:

string(15) "This is title 1"

There is native SimpleXML method SimpleXMLElement::asXML Depending on parameter it writes SimpleXMLElement to xml 1.0 file, Yes

$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());

The following is a recursive function that will typecast all single-child elements to a 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

참고URL : https://stackoverflow.com/questions/416548/forcing-a-simplexml-object-to-a-string-regardless-of-context

반응형