简体   繁体   中英

XML help needed for extracting xml node text and child nodes (PHP)

Consider the following xml snippet.

<s1>
 S1 Tag: s1 content 1
 <test1>Test1 Tag: content</test1>
 S1 Tag: s1 content 2
 <test2>Test2 Tag: content</test2>
 S1 Tag: s1 content 3
</s1>

I want to extract <s1> tag text ( S1 Tag: s1 content 1, S1 Tag: s1 content 2, S1 Tag: s1 content 3 ) and all of its child tags ( <test1> and <test2> ) along with its content ( Test1 Tag: content, Test2 Tag: content ).

The output could be in any format eg (finally i have to persist it in db and will retrieve to produce the same xml again)

  S1 tag: S1 Tag: s1 content 1

  test1 tag: Test1 Tag: content

  S1 Tag: s1 content 2

  test2 tag: Test2 Tag: content

  S1 Tag: s1 content 3

Use simplexml:

   $stuff = " <s1>
 S1 Tag: s1 content 1
 <test1>Test1 Tag: content</test1>
 S1 Tag: s1 content 2
 <test2>Test2 Tag: content</test2>
 S1 Tag: s1 content 3
</s1>";

    $xml = simplexml_load_string($stuff);

    $test1 = (string) $xml->s1->test1;

    write_to_db($field, $test1);

是否与通过以下正则表达式剥离所有标签相同?

preg_replace('<[^>]+>', ' ', $xmlStr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM