Jump to content

Replacing XML elements


morningstar

Recommended Posts

I need to parse XML like the block below:

 

<body>
    <character>
        <favorites>Your lucky number is <number id="1" min="5" max="10" />. Your favorite color is <color id="2" />. Your favorite food is <food id="2" type="desserts" /></favorites>
    </character>
</body>

 

SimpleXML works great for everything except the content between the <favorites> tag. I want to replace the empty elements (<number />, <color />, and <food />) with randomly generated words and numbers while retaining their position in the string. E.g. the desired result should look something like:

 

Your lucky number is 7. Your favorite color is green. Your favorite food is pie.

 

SimpleXML will load these as:

 

object(SimpleXMLElement)#4 (3) {
  ["number"]=>
  object(SimpleXMLElement)#3 (1) {
    ["@attributes"]=>
    array(3) {
      ["id"]=>
      string(1) "1"
      ["min"]=>
      string(1) "5"
      ["max"]=>
      string(2) "10"
    }
  }
  ["color"]=>
  object(SimpleXMLElement)#5 (1) {
    ["@attributes"]=>
    array(1) {
      ["id"]=>
      string(1) "2"
    }
  }
  ["food"]=>
  object(SimpleXMLElement)#6 (1) {
    ["@attributes"]=>
    array(2) {
      ["id"]=>
      string(1) "3"
      ["type"]=>
      string( "desserts"
    }
  }
}

 

And the value of the <favorites></favorites> element is:

 

object(SimpleXMLElement)#2 (1) {
  ["favorites"]=>
  string(70) "Your lucky number is . Your favorite color is . Your favorite food is "
}

 

I wanted to use preg_replace_callback before parsing the XML with SimpleXML, but the problem is the attributes of the empty elements won't be very regular. Sometimes they won't all be there, will be in a different order, etc.

 

So is there a way to replace the empty elements using SimpleXML, or regex before SimpleXML, or some other way?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/135823-replacing-xml-elements/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.