Parse XML to HTML with PHP SimpleXMLElement

2019-08-12 23:56发布

问题:

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.

回答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


回答2:

You can also use XPath.

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