使用PHP从xml中提取多个标签

时间:2012-07-08 21:12:28

标签: php xml

这是我的address.xml

<?xml version="1.0" ?>
<!--Sample XML document -->
<AddressBook>
    <Addressentry>
        <firstName>jack</firstName>
        <lastName>S</lastName>
        <Address>2899,Ray Road</Address>
        <Email>jkjsvsdka@ghu.edu</Email>
    </Addressentry>
    <Addressentry>
        <firstName>Sid</firstName>
        <lastName>K</lastName>
        <Address>238,Baseline Road,TX</Address>
        <Email>sk@ghu.edu</Email>
        <Email>sk@gmail.com</Email>
    </Addressentry>
    <Addressentry>
        <firstName>Satya</firstName>
        <lastName>Yar</lastName>
        <Address>6,Rural Road,Tempe,AZ</Address>
        <Email>syarlag@ghu.edu</Email>
       <Email>ssya@gmail.com</Email>
        <Email>satag@yahoo.com</Email>
    </Addressentry>

</AddressBook>

我正在尝试使用PHP代码加载所有条目,如下所示。每个地址都可以有一个或多个标签。现在从下面的代码我只能提取一个标签。我的问题是如何提取与特定地址相关联的所有标签。我希望在同一行打印所有电子邮件。

<?php
$theData = simplexml_load_File("address.xml");

foreach($theData->Addressentry as $theAddress) {
    $theFirstName = $theAddress->firstName;
    $theLastName = $theAddress->lastName;
    $theAdd = $theAddress->Address;


    echo "<p>".$theFirstName."
    ".$theLastName."<br/>
    ".$theAdd."<br/>
    ".$theAddress->Email."<br/>
    </p>";


    unset($theFirstName);
    unset($theLastName);
    unset($theAdd);
    unset($theEmail);
}
?>

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

$emails = array();
foreach ($theAddress->Email as $email) {
    $emails[] = $email;
}
echo "<p>".$theFirstName."
    ".$theLastName."<br/>
    ".$theAdd."<br/>
    ".implode(', ', $emails)."<br/>
    </p>";