1

I am having some issues with SimpleXMLElement that I was hoping to get some help.

I was reading about SimpleXMLElement and I built a PHP page to parse this XML:

<?xml version='1.0'?>
<AdXML>

<Response>
    <Campaign>
        <Overview>
            <Name>strip</Name>
                <Description>category</Description>
                <Status>L</Status>
        </Overview>
        <Pages>
            <Url>page01</Url>
            <Url>page02</Url>
            <Url>page03</Url>
        </Pages>
    </Campaign>
</Response>
</AdXML>

Tag "Pages" can have any number of tags "Url" other tags might have only one value, like the tag "Name" for example.

Reading about SimpleXMLElement I ended up with the following code:

$xmlparsed = new SimpleXMLElement($xml); //my xml is being sent as variable

To display single values I am using the code below without a problem:

<?php echo $xmlparsed->Response[0]->Campaign[0]->Overview[0]->Name;?>

Everything works fine. But when I try to parse a tag with multiple lines I get only one line, and everytime I refresh the page it gives me a different "url" value. This is the code I am using:

<?php foreach ($xmlparsed->Response->Campaign->Pages as $Pages) {echo $Pages->Url, PHP_EOL;} ?>

According to PHP's site: http://php.net/manual/en/simplexml.examples-basic.php this should work, but it isn't.

Since I am not expert on PHP I am testing code on a trial-and-error basis.

What am I doing wrong here?

thanks in advance for any help.

2 Answers 2

1

You only have one Pages so you are only entering that foreach once. Try looping on the urls.

$xml = "<?xml version='1.0'?>
<AdXML>

<Response>
    <Campaign>
        <Overview>
            <Name>strip</Name>
                <Description>category</Description>
                <Status>L</Status>
        </Overview>
        <Pages>
            <Url>page01</Url>
            <Url>page02</Url>
            <Url>page03</Url>
        </Pages>
    </Campaign>
</Response>
</AdXML>";
$xmlparsed = new SimpleXMLElement($xml);
foreach ($xmlparsed->Response->Campaign->Pages->Url as $url) {
    echo $url, PHP_EOL;
}

Output:

page01
page02
page03
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use XPath.

foreach( $xml->xpath( 'Response/Campaign/Pages/Url' ) as $url ) {
    echo $url;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.