0

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 e.g. (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
Shahid
  • 1,051
  • 1
  • 10
  • 14

2 Answers2

0

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);
  • use the concept. actual code is not meant to work by copy/paste – rahimvirani Feb 24 '12 at 17:43
  • hmmmmm... yes i understand .. the main problem i am facing is to retrieve s1 content and all of it child tags. actually my code just extract the only "S1 Tag: s1 content 1" content and ignore the rest – Shahid Feb 24 '12 at 17:47
  • this is because you need a root node. wrap the whole thing in a node: $string = " S1 Tag: s1 content 1 Test1 Tag: content S1 Tag: s1 content 2 Test2 Tag: content S1 Tag: s1 content 3 "; $xml = simplexml_load_string($string); echo (string) $xml->s1; – rahimvirani Feb 25 '12 at 00:41
-1

Is it same as to strip all tags via following regex

preg_replace('<[^>]+>', ' ', $xmlStr)
d-live
  • 7,926
  • 3
  • 22
  • 16
  • In fact I want to save xml to db and then have to rebuild the xml from db again. Therefore, replacing tag will will not be helpful at all. – Shahid Feb 24 '12 at 17:42