PHP: SimpleXML question

Discussion in 'Web Design and Development' started by carlosbutler, Apr 3, 2011.

  1. carlosbutler macrumors 6502a

    carlosbutler

    Joined:
    Feb 24, 2008
    Location:
    London City
    #1
    Hello!

    I am trying to go through an XML file and take out certain parts of it.

    As seen below, the Line is a child of LineStatus. I would like to remove, say, the LineStatus block that Line ID="2" is in from the XML document. I know the format of the XML is a bit strange, but surely there is a way of doing this?

    The structure of it is like this:
    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <ArrayOfLineStatus xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://webservices.lul.co.uk/">
      
      <LineStatus ID="0" StatusDetails="">
        <BranchDisruptions />
        <Line ID="1" Name="Name1" />
        <Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
          <StatusType ID="1" Description="Line" />
        </Status>
      </LineStatus>
      
      <LineStatus ID="1" StatusDetails="Problem to service">
        <BranchDisruptions />
        <Line ID="2" Name="Name2" />
        <Status ID="PC" CssClass="DisruptedService" Description="Part Closure" IsActive="true">
          <StatusType ID="1" Description="Line" />
        </Status>
      </LineStatus>
      
    </ArrayOfLineStatus>
    I am doing this in PHP and reading the file:
    PHP:

    $xmlstr 
    file_get_contents('an.xml');
    $sitemap = new SimpleXMLElement($xmlstr);

    foreach(
    $sitemap->children() as $child) {    
        foreach(
    $child->children() as $subchild) {        
            foreach(
    $subchild->attributes() as $subchildAttr) {            
                if (
    $subchildAttr->getName() == 'Name' && ($subChildAttr != "82" || $subChildAttr != "81")) {
                    echo 
    $subchild->asXML()."\n";
                }
            }
        }
    }
    ?>
    Thanks!
     
  2. snebes macrumors 6502a

    Joined:
    Apr 20, 2008
    #2
    If there are manageable blocks, perhaps you should just use a regular expression to match/remove them. Or are you looking for more complex alterations?
     
  3. carlosbutler thread starter macrumors 6502a

    carlosbutler

    Joined:
    Feb 24, 2008
    Location:
    London City
    #3
    Just to remove a block that will keep the same form. But how would a regex help? (not being funny... Just really not sure how I would implement it)
     
  4. snebes macrumors 6502a

    Joined:
    Apr 20, 2008
    #4
    You would read the XML file like a text file, not into an XML reader. That way you could just do something like this:

    PHP:
    $xmlstr file_get_contents('an.xml');
    $result preg_replace("#<LineStatus ID=\"1\".*?</LineStatus>#si"""$xmlstr);
    // save $result to file or whatever.
     

Share This Page