如何将多个复选框值传递给php

问题描述 投票:2回答:1

目前,我有一个HTML表单,该表单收集有关某些文件的一些元数据,每个用户都将填写一些字段。我想注册一些有关数据的关键字。我可以要求他们在一个普通的文本框中手工编写关键字,但是我希望有一个大约10/15值的复选框列表。

然后我只需要使用$_POST将检查的值传递给PHP文件。我的问题是我为这些值分配了一个变量,然后在DOM事件中调用了该变量。我正在生成一个XML文件,目前我已准备好HTML,可以在文本输入中注册这些关键字。通过阅读此处的其他问题,我了解如何创建复选框,并将其作为数组传递给PHP。但是我不明白如何将该数组传递给$dom->createElement情况,最好用逗号分隔。

PHP

//Pull data from HTML form
$keywordsString = $_POST['keywords'];

// Creates xml document
$dom = new DOMDocument();
    $dom->encoding = 'utf-8';
    $dom->xmlVersion = '1.0';
    $dom->formatOutput = true;

$xmlFileName = 'example_example.xml';

// Adds metadata to xml
$metadata = $dom->createElement('MD_Metadata');

    $idInfo = $dom->createElement('identificationInfo');
        $descriptiveKeywords = $dom->createElement('descriptiveKeywords');
                $CharacterString = $dom->createElement('CharacterString', $keywordsString);
                $descriptiveKeywords->appendChild($CharacterString);
            $idInfo->appendChild($descriptiveKeywords);
    $metadata->appendChild($idInfo);

$dom->appendChild($metadata);

$dom->save($xmlFileName);

我不知道如何将复选框值传递给$keywordsString,但用逗号分隔。其余的我可以理解和编写,并使用有关此类问题的其他问题。

感谢您提供的所有帮助。

php html post dom checkbox
1个回答
0
投票

您的html应该看起来像这样:

 <form action="" method="post">
    <input name="choice[]" type="checkbox" value="1" /> 
    <input name="choice[]" type="checkbox" value="2" /> 
    <input name="choice[]" type="checkbox" value="3" /> 
    <input name="choice[]" type="checkbox" value="4" /> 
    <input type="submit" value="order" />
  </form>

在PHP中,您可以像这样使用foreach循环进行迭代,以检索您选择的选项:

foreach($_POST['choice'] as $val )
{
echo $val . "<br>";
}
© www.soinside.com 2019 - 2024. All rights reserved.